<template>
  <div class="tab-pane-cover">
    <div class="treegrid-source" v-if="isTreeGridNavMode">
      <span class="title">
        {{
          $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.selectdatasource')
        }}
      </span>
      <div class="source-title">
        <span>
          {{
            sourceTable === ''
              ? $srv.getI18nByPath(
                  'oSetupPanel.SetupAttrLibfield.notableselected'
                )
              : $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.source') +
                $srv.getI18nBySrv(sourceTable)
          }}
        </span>
        <div>
          <Button
            size="small"
            type="primary"
            @click="selectSourceTableFields"
            :disabled="sourceTable === ''"
          >
            {{
              $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.selectfield')
            }}
          </Button>
          <Button size="small" type="primary" @click="selectSourceTable">
            {{
              $srv.getI18nByPath(
                'oSetupPanel.SetupAttrLibfield.selectsourcetable'
              )
            }}
          </Button>
          <Button
            size="small"
            @click="sourceDelete"
            :disabled="sourceDeleteDisable"
          >
            {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.delete') }}
          </Button>
        </div>
      </div>
      <div
        class="source-table"
        v-if="
          current.config.tableDataSource &&
            current.config.tableDataSource.main &&
            current.config.tableDataSource.main.fields
        "
      >
        <Table
          :columns="sourceMainColumn"
          :data="current.config.tableDataSource.main.fields"
          ref="sourceMainTbl"
          highlight-row
          disabled-hover
          @on-selection-change="sourceSelectChange"
        >
          <template slot-scope="{ index }" slot="keyField">
            <Checkbox
              v-model="
                current.config.tableDataSource.main.fields[index].keyField
              "
              @on-change="selectSourceKeyField(index)"
            >
            </Checkbox>
          </template>
          <template slot-scope="{ index }" slot="childField">
            <Checkbox
              v-model="
                current.config.tableDataSource.main.fields[index].childField
              "
              @on-change="selectSourceChildField(index, $event)"
            >
            </Checkbox>
          </template>
          <template slot-scope="{ index }" slot="isShow">
            <Checkbox
              v-model="current.config.tableDataSource.main.fields[index].isShow"
              @on-change="selectSourceIsShow(index, $event)"
            >
            </Checkbox>
          </template>
          <template slot-scope="{ index }" slot="filter">
            <i-input
              v-model="current.config.tableDataSource.main.fields[index].filter"
              @on-blur="saveChanges(index, $event)"
            >
            </i-input>
          </template>
        </Table>
      </div>
    </div>

    <div class="common-source" v-else>
      <div
        class="ref-table"
        v-if="$srv.getx(panelItems, 'refTable.isShow', false)"
      >
        <span class="ref-title">{{ $srv.getI18nByValue('引用表格') }}</span>
        <o-m2o-selector
          :tTable="$srv.globalVar.tableName.SYS_FUN"
          :tField="$srv.globalVar.fieldName.title"
          v-model="refTable"
          @model-change="refTableChange"
        >
        </o-m2o-selector>
      </div>

      <div
        :class="[
          'lib-group',
          selectedLib.length === 1 ? 'no-group' : '',
          activeGroup === idx ? 'active' : ''
        ]"
        v-for="(item, idx) of selectedLib"
        :key="idx"
      >
        <div class="group-title" @click="groupSwitch(idx)">
          <span class="title">{{ $srv.getI18nBySrv(item.title) }}</span>
          <icon type="ios-arrow-down"></icon>
        </div>
        <span class="title">
          {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.selectfield') }}
        </span>
        <div class="group-content">
          <div
            class="lib-group-section"
            v-for="(item2, idx2) of item.content"
            :key="idx2"
          >
            <div class="group-func">
              <Button
                class="lib-add-unique"
                size="small"
                @click="addIndex(idx, 'uniqIndex')"
                v-show="
                  panelItems['btnUnique'] ? panelItems.btnUnique.isShow : false
                "
                :disabled="
                  panelItems['btnUnique'] ? panelItems.btnUnique.disabled : true
                "
              >
                {{
                  $srv.getI18nByPath(
                    'oSetupPanel.SetupAttrLibfield.uniqueindex'
                  )
                }}
              </Button>
              <Button
                class="lib-add-index"
                size="small"
                @click="addIndex(idx, 'index')"
                v-show="
                  panelItems['btnIndex'] ? panelItems.btnIndex.isShow : false
                "
                :disabled="
                  panelItems['btnIndex'] ? panelItems.btnIndex.disabled : true
                "
              >
                {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.index') }}
              </Button>
            </div>
            <div class="group-section-title">
              <span class="title">{{ $srv.getI18nBySrv(item2.title) }}</span>
              <Button
                :ref="getRef('btnLibAdd', idx, idx2)"
                v-show="
                  panelItems['btnSelect'] ? panelItems.btnSelect.isShow : false
                "
                :disabled="
                  panelItems['btnSelect'] ? panelItems.btnSelect.disabled : true
                "
                class="lib-add"
                size="small"
                @click="selectFieldForTable(idx, idx2, 'btnLibAdd')"
                type="primary"
              >
                <!-- 选取 -->
                {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.select') }}
              </Button>
              <Button
                :ref="getRef('btnLibDel', idx, idx2)"
                class="lib-delete"
                size="small"
                @click="beforeRemoveFieldsFromTable(idx, idx2, item.title)"
                v-show="
                  panelItems['btnDelete'] ? panelItems.btnDelete.isShow : false
                "
                :disabled="
                  panelItems['btnDelete'] ? panelItems.btnDelete.disabled : true
                "
              >
                {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.delete') }}
              </Button>
              <Button
                :ref="getRef('btnLibDown', idx, idx2)"
                class="lib-down"
                size="small"
                icon="md-arrow-down"
                @click="moveFields(idx, idx2, 'btnLibDown')"
                v-show="
                  panelItems['btnDown'] ? panelItems.btnDown.isShow : false
                "
                :disabled="
                  panelItems['btnDown'] ? panelItems.btnDown.disabled : true
                "
              >
              </Button>
              <Button
                :ref="getRef('btnLibUp', idx, idx2)"
                class="lib-up"
                size="small"
                icon="md-arrow-up"
                @click="moveFields(idx, idx2, 'btnLibUp')"
                v-show="panelItems['btnUp'] ? panelItems.btnUp.isShow : false"
                :disabled="
                  panelItems['btnUp'] ? panelItems.btnUp.disabled : true
                "
              >
              </Button>
              <Button
                :ref="getRef('btnLibGetField', idx, idx2)"
                type="primary"
                class="lib-get-field"
                size="small"
                @click="getFields(idx, idx2, 'btnLibGetField')"
                v-show="
                  panelItems['btnGetField']
                    ? panelItems.btnGetField.isShow
                    : false
                "
                :disabled="
                  panelItems['btnGetField']
                    ? panelItems.btnGetField.disabled
                    : true
                "
              >
                {{ $srv.getI18nByValue('同步字段') }}
              </Button>
            </div>

            <div class="tab-box selected-lib">
              <div class="selected-lib-table">
                <c-table
                  :columns="selectedLibColumn"
                  :ref="getRef('libTbl', idx, idx2)"
                  @on-selection-change="
                    tableSelectionChange(idx, idx2, 'libTbl', $event)
                  "
                  @on-row-click="handleRowClick"
                  @compBoxInfo="loadTableData"
                />
              </div>
            </div>
          </div>
          <div
            class="tab-box unique-index"
            v-if="panelItems.uniqueIndexes.isShow"
          >
            <span class="title">
              {{
                $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.uniqueindex')
              }}
            </span>
            <div v-if="!$srv.utils.noValue(uniqueIndexes['mark_' + idx])">
              <div
                class="index-cell"
                v-for="(uitem, uidx) of uniqueIndexes['mark_' + idx]"
                :key="uidx"
              >
                <div class="index-cell-tit">
                  <span class="index-cell-id">ID</span>
                  <span class="index-cell-name">
                    {{
                      $srv.getI18nByPath(
                        'oSetupPanel.SetupAttrLibfield.fieldname'
                      )
                    }}
                  </span>
                  <span class="index-cell-name-i18n">
                    {{
                      $srv.getI18nByPath(
                        'oSetupPanel.SetupAttrLibfield.locallanguage'
                      )
                    }}
                  </span>
                  <Icon
                    type="md-close"
                    @click="beforeRemoveIndex(idx, uidx, 'uniqIndex')"
                  />
                </div>
                <div
                  class="index-cell-cont"
                  v-for="(uitem2, uidx2) of uitem"
                  :key="uidx2"
                >
                  <span class="index-cell-id" :title="uitem2.id">{{
                    uitem2.id
                  }}</span>
                  <span class="index-cell-name">{{ uitem2.name }}</span>
                  <span class="index-cell-name-i18n">
                    {{ $srv.getI18nBySrv(uitem2.name) }}
                  </span>
                </div>
              </div>
            </div>
            <div v-else class="empty">
              {{
                $srv.getI18nByPath(
                  'oSetupPanel.SetupAttrLibfield.nouniqueindexisset'
                )
              }}
            </div>
          </div>
          <div class="divider-empty-thin"></div>
          <div class="divider-empty-thin"></div>
          <Divider />
          <div class="divider-empty-thin"></div>
          <div class="tab-box index" v-if="panelItems.indexes.isShow">
            <span class="title">
              {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.index') }}
            </span>
            <div v-if="!$srv.utils.noValue(indexes['mark_' + idx])">
              <div
                class="index-cell"
                v-for="(iitem, iidx) of indexes['mark_' + idx]"
                :key="iidx"
              >
                <div class="index-cell-tit">
                  <span class="index-cell-id">ID</span>
                  <span class="index-cell-name">
                    {{
                      $srv.getI18nByPath(
                        'oSetupPanel.SetupAttrLibfield.fieldname'
                      )
                    }}
                  </span>
                  <span class="index-cell-name-i18n">
                    {{
                      $srv.getI18nByPath(
                        'oSetupPanel.SetupAttrLibfield.locallanguage'
                      )
                    }}
                  </span>
                  <Icon
                    type="md-close"
                    @click="beforeRemoveIndex(idx, iidx, 'index')"
                  />
                </div>
                <div
                  class="index-cell-cont"
                  v-for="(iitem2, iidx2) of iitem"
                  :key="iidx2"
                >
                  <span class="index-cell-id" :title="iitem2.id">{{
                    iitem2.id
                  }}</span>
                  <span class="index-cell-name">{{ iitem2.name }}</span>
                  <span class="index-cell-name-i18n">
                    {{ $srv.getI18nBySrv(iitem2.name) }}
                  </span>
                </div>
              </div>
            </div>
            <div v-else class="empty">
              {{
                $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.noindexset')
              }}
            </div>
          </div>
          <div class="divider-empty-thin"></div>
          <div class="divider-empty-thin"></div>
          <Divider />
          <div class="divider-empty-thin"></div>
          <div
            class="tab-box"
            v-if="panelItems.rules.isShow && item.title !== 'gauge_outfit'"
          >
            <o-rules-setting
              :config="
                rules['mark_' + idx]
                  ? rules['mark_' + idx]
                  : (rules['mark_' + idx] = [])
              "
              @change="saveChanges"
            >
            </o-rules-setting>
          </div>
          <div
            class="tab-box"
            v-if="panelItems.headerGroup.isShow && headerGroup['mark_' + idx]"
          >
            <o-header-group-setting
              :config="headerGroup['mark_' + idx]"
              @change="saveChanges"
            >
            </o-header-group-setting>
          </div>
          <div
            class="tab-box"
            v-if="panelItems.charts.isShow && charts['mark_' + idx]"
          >
            <o-chart-setting
              :config="charts['mark_' + idx]"
              @change="saveChanges"
            >
            </o-chart-setting>
          </div>
        </div>
      </div>
    </div>
    <!-- 详细设置 -->
    <div
      class="detail-panel"
      v-if="
        editingLibIndex !== null &&
          editingLibSubIndex !== null &&
          selectedLibData
      "
      :style="detailPanelStyle"
    >
      <div class="title">
        <span>
          {{
            $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.detailedsettings')
          }}
        </span>
        <span class="sel-row-field">{{
          $srv.getI18nByValue('字段') +
            '：' +
            $srv.getI18nBySrv(
              selectedLibData[editingLibIndex][editingLibSubIndex].field
            )
        }}</span>
        <Icon @click="hideDetailPanel" type="md-close" />
      </div>
      <!-- <div class="divider-empty-thin"></div>
      <div class="divider-empty-thin"></div> -->
      <Collapse v-model="detailPanelName">
        <!-- 字段属性配置 -->
        <Panel
          v-show="$srv.getx(panelFieldDetail, 'fieldProperties.isShow', false)"
          name="fieldProperties"
        >
          {{
            $srv.getI18nByPath(
              'oSetupPanel.SetupAttrLibfield.fieldpropertyconfiguration'
            )
          }}
          <template #content>
            <div class="detail-panel-box box-h">
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxIsShow']
                    ? panelFieldDetail.chkBoxIsShow.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.whethertoshow'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    panelFieldDetail['chkBoxIsShow']
                      ? panelFieldDetail.chkBoxIsShow.disabled
                      : true
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex].isShow
                  "
                  @on-change="saveChanges"
                >
                </Checkbox>
              </div>
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxIsNotNull']
                    ? panelFieldDetail.chkBoxIsNotNull.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.valueisnotempty'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    panelFieldDetail['chkBoxIsNotNull']
                      ? panelFieldDetail.chkBoxIsNotNull.disabled
                      : true
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex].notNull
                  "
                  @on-change="saveChanges"
                >
                </Checkbox>
              </div>
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxDescField']
                    ? panelFieldDetail.chkBoxDescField.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.descriptionfield'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    panelFieldDetail['chkBoxDescField']
                      ? panelFieldDetail.chkBoxDescField.disabled
                      : true
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex].isDes
                  "
                  @on-change="isDesChange"
                >
                </Checkbox>
              </div>
            </div>
            <div class="detail-panel-box box-h">
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxIsItnecessary']
                    ? panelFieldDetail.chkBoxIsItnecessary.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.isitnecessary'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    panelFieldDetail['chkBoxIsItnecessary']
                      ? panelFieldDetail.chkBoxIsItnecessary.disabled
                      : true
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .required
                  "
                  @on-change="saveChanges"
                >
                </Checkbox>
              </div>
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxProhibitinput']
                    ? panelFieldDetail.chkBoxProhibitinput.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.prohibitinput'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    panelFieldDetail['chkBoxProhibitinput']
                      ? panelFieldDetail.chkBoxProhibitinput.disabled
                      : true
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .disabled
                  "
                  @on-change="saveChanges"
                >
                </Checkbox>
              </div>
              <!-- 原程序描述basePanel baseGrid专用 -->
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxDevFilter']
                    ? panelFieldDetail.chkBoxDevFilter.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.defaultfilter'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    panelFieldDetail['chkBoxDevFilter']
                      ? panelFieldDetail.chkBoxDevFilter.disabled
                      : true
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .defaultFilter
                  "
                  @on-change="saveChanges"
                >
                </Checkbox>
              </div>
              <!-- 当数据相同时相邻单元格是否进行合并 baseGrid专用 -->
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxMergeCells']
                    ? panelFieldDetail.chkBoxMergeCells.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.whethermergecells'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    panelFieldDetail['chkBoxMergeCells']
                      ? panelFieldDetail.chkBoxDevFilter.disabled
                      : true
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .mergeCells
                  "
                  @on-change="saveChanges"
                >
                </Checkbox>
              </div>
              <!-- graph专用 -->
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxNodeData']
                    ? panelFieldDetail.chkBoxNodeData.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.nodeData'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    panelFieldDetail['chkBoxNodeData']
                      ? panelFieldDetail.chkBoxNodeData.disabled
                      : true
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .nodeData
                  "
                  @on-change="isNodeDataChange"
                >
                </Checkbox>
              </div>
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxFixedLeft']
                    ? panelFieldDetail.chkBoxFixedLeft.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.fixedLeft'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    (panelFieldDetail['chkBoxFixedLeft']
                      ? panelFieldDetail.chkBoxFixedLeft.disabled
                      : true) ||
                      selectedLibData[editingLibIndex][editingLibSubIndex]
                        .fixedRight
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .fixedLeft
                  "
                  @on-change="saveChanges"
                >
                </Checkbox>
              </div>
              <div
                class="check"
                v-show="
                  panelFieldDetail['chkBoxFixedRight']
                    ? panelFieldDetail.chkBoxFixedRight.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.fixedRight'
                    )
                  }}:</span
                >
                <Checkbox
                  :disabled="
                    (panelFieldDetail['chkBoxFixedRight']
                      ? panelFieldDetail.chkBoxFixedRight.disabled
                      : true) ||
                      selectedLibData[editingLibIndex][editingLibSubIndex]
                        .fixedLeft
                  "
                  size="small"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .fixedRight
                  "
                  @on-change="saveChanges"
                >
                </Checkbox>
              </div>
            </div>
            <!-- <div class="detail-panel-box box-h">
        <div class="check">
          <span> {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.noDragging') }}:</span>
          <Checkbox
            size="small"
            v-model="
              selectedLibData[editingLibIndex][editingLibSubIndex].noDragging
            "
            @on-change="saveChanges"
          >
          </Checkbox>
        </div>
      </div> -->
            <div class="divider-empty-thin"></div>
            <Divider />
          </template>
        </Panel>
        <!-- 字段数据格式配置————（默认值、字段别名、最小宽度、对齐方式、汇总方式、字段数据类型） -->
        <Panel
          v-show="$srv.getx(panelFieldDetail, 'fieldDataFormat.isShow', false)"
          name="dataFormat"
        >
          {{
            $srv.getI18nByPath(
              'oSetupPanel.SetupAttrLibfield.fielddataformatconfiguration'
            )
          }}
          <template #content>
            <div
              class="detail-panel-box"
              v-show="
                panelFieldDetail['inputDefVal']
                  ? panelFieldDetail.inputDefVal.isShow
                  : false
              "
            >
              <div class="input">
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.defaults'
                    )
                  }}:
                </span>
                <i-input
                  :disabled="
                    panelFieldDetail['inputDefVal']
                      ? panelFieldDetail.inputDefVal.disabled
                      : true
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .defValue
                  "
                  @on-blur="saveChanges"
                >
                </i-input>
              </div>
            </div>
            <div
              class="detail-panel-box"
              v-show="
                panelFieldDetail['placeholder']
                  ? panelFieldDetail.placeholder.isShow
                  : false
              "
            >
              <div class="input">
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.placeholder'
                    )
                  }}:
                </span>
                <i-input
                  :disabled="
                    panelFieldDetail['placeholder']
                      ? panelFieldDetail.placeholder.disabled
                      : true
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .placeholder
                  "
                  @on-blur="saveChanges"
                >
                </i-input>
              </div>
            </div>
            <!-- 字段前/后缀 -->
            <div
              class="detail-panel-box"
              v-if="
                $srv.getx(panelFieldDetail, 'fieldPrefix.isShow', false, v => {
                  if (
                    v &&
                    !$srv.utils.has(
                      selectedLibData[editingLibIndex][editingLibSubIndex],
                      'fieldPrefix'
                    )
                  ) {
                    selectedLibData[editingLibIndex][editingLibSubIndex][
                      'fieldPrefix'
                    ] = panelFieldDetail.fieldPrefix.defVal;
                  }
                })
              "
            >
              <div class="input">
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.fieldprefix'
                    )
                  }}:
                </span>
                <field-introduction-setting
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .fieldPrefix
                  "
                  :disabled="
                    panelFieldDetail['fieldPrefix']
                      ? panelFieldDetail.fieldPrefix.disabled
                      : true
                  "
                  @change="saveChanges"
                ></field-introduction-setting>
              </div>
            </div>
            <!-- 字段后缀 -->
            <div
              class="detail-panel-box"
              v-if="
                $srv.getx(panelFieldDetail, 'fieldSuffix.isShow', false, v => {
                  if (
                    v &&
                    !$srv.utils.has(
                      selectedLibData[editingLibIndex][editingLibSubIndex],
                      'fieldSuffix'
                    )
                  ) {
                    selectedLibData[editingLibIndex][editingLibSubIndex][
                      'fieldSuffix'
                    ] = panelFieldDetail.fieldSuffix.defVal;
                  }
                })
              "
            >
              <div class="input">
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.fieldSuffix'
                    )
                  }}:
                </span>
                <field-introduction-setting
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .fieldSuffix
                  "
                  :disabled="
                    panelFieldDetail['fieldSuffix']
                      ? panelFieldDetail.fieldSuffix.disabled
                      : true
                  "
                  @change="saveChanges"
                ></field-introduction-setting>
              </div>
            </div>
            <!-- 字段别名 -->
            <div class="detail-panel-box">
              <div
                class="input"
                v-show="
                  panelFieldDetail['i18nFieldAlias']
                    ? panelFieldDetail.i18nFieldAlias.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.fieldalias'
                    )
                  }}:
                </span>

                <o-i18n-selector
                  :disabled="
                    panelFieldDetail['i18nFieldAlias']
                      ? panelFieldDetail.i18nFieldAlias.disabled
                      : true
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex].comment
                  "
                  @on-blur="saveChanges"
                  :placeholder="$srv.getLangPathByValue('请输入别名')"
                  :compBoxInfo="GT_compBoxInfo"
                ></o-i18n-selector>
              </div>
              <div
                class="input"
                v-show="
                  panelFieldDetail['inputMinWidth']
                    ? panelFieldDetail.inputMinWidth.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.minimumwidth'
                    )
                  }}:
                </span>
                <i-input
                  :disabled="
                    panelFieldDetail['inputMinWidth']
                      ? panelFieldDetail.inputMinWidth.disabled
                      : true
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .minWidth
                  "
                  @on-blur="saveChanges"
                >
                </i-input>
              </div>
              <!-- <div
                class="input"
                v-if="
                  $srv.getx(panelFieldDetail, 'inputWidth', false, v => {
                    const span =
                      selectedLibData[editingLibIndex][editingLibSubIndex].span;
                    if (
                      !selectedLibData[editingLibIndex][editingLibSubIndex]
                        .span ||
                      selectedLibData[editingLibIndex][editingLibSubIndex]
                        .span <= 2
                    ) {
                      selectedLibData[editingLibIndex][
                        editingLibSubIndex
                      ].span = 6;
                    }
                  })
                "
              > -->
              <div
                class="input"
                v-if="
                  $srv.getx(panelFieldDetail, 'inputWidth', false, v => {
                    const span =
                      selectedLibData[editingLibIndex][editingLibSubIndex].span;
                    selectedLibData[editingLibIndex].forEach(el => {
                      if (
                        current.name === 'BasePanel' ||
                        current.name === 'cBaseForm'
                      ) {
                        if (!el.span || el.span <= 2) {
                          el.span = 6;
                          saveChanges();
                        }
                      } else {
                        el.span = undefined;
                      }
                    });
                  })
                "
              >
                <span :title="$srv.getI18nByValue('显示宽度24等分')">
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.initwidth'
                    )
                  }}:
                </span>
                <InputNumber
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex].span
                  "
                  :disabled="
                    panelFieldDetail['inputWidth']
                      ? panelFieldDetail.inputWidth.disabled
                      : true
                  "
                  :min="2"
                  :max="24"
                  @on-change="saveChanges"
                  @on-blur="saveChanges"
                  controls-outside
                />
              </div>
              <div
                class="select"
                v-show="
                  panelFieldDetail['inputAlignment']
                    ? panelFieldDetail.inputAlignment.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.alignment'
                    )
                  }}:
                </span>
                <Select
                  :disabled="
                    panelFieldDetail['inputAlignment']
                      ? panelFieldDetail.inputAlignment.disabled
                      : true
                  "
                  clearable
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex].align
                  "
                  @on-change="saveChanges"
                >
                  <Option value="left">
                    {{
                      $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.left')
                    }}
                  </Option>
                  <Option value="center">
                    {{
                      $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.center')
                    }}
                  </Option>
                  <Option value="right">
                    {{
                      $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.right')
                    }}
                  </Option>
                </Select>
              </div>
              <div
                class="input"
                v-show="
                  panelFieldDetail['inputAppSort']
                    ? panelFieldDetail.inputAppSort.isShow
                    : false
                "
              >
                <span
                  >App
                  {{
                    $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.sort')
                  }}:
                </span>
                <i-input
                  :disabled="
                    panelFieldDetail['inputAppSort']
                      ? panelFieldDetail.inputAppSort.disabled
                      : true
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .appWeight
                  "
                  @on-blur="saveChanges"
                >
                </i-input>
              </div>
            </div>
            <div class="divider-empty"></div>
            <div class="divider-empty-thin"></div>
            <Divider />
            <div class="divider-empty-thin"></div>
            <!-- 汇总方式（vxe-table） -->
            <div class="detail-panel-box">
              <div class="divider-empty-thin"></div>
              <div class="formatter">
                <div
                  class="input"
                  v-show="
                    panelFieldDetail['inputSummaryMethod']
                      ? panelFieldDetail.inputSummaryMethod.isShow
                      : false
                  "
                >
                  <span>
                    <!-- 汇总方式 -->
                    {{
                      $srv.getI18nByPath(
                        'oSetupPanel.SetupAttrLibfield.aggregatemethod'
                      )
                    }}
                    :
                  </span>
                  <Select
                    :disabled="
                      panelFieldDetail['inputSummaryMethod']
                        ? panelFieldDetail.inputSummaryMethod.disabled
                        : true
                    "
                    clearable
                    v-model="
                      selectedLibData[editingLibIndex][editingLibSubIndex]
                        .footerMethod
                    "
                    @on-change="saveChanges"
                  >
                    <Option
                      v-for="item in footerMethodList"
                      :value="item.value"
                      :key="item.value"
                    >
                      {{ item.label }}
                    </Option>
                  </Select>
                </div>
              </div>
              <div
                class="divider-empty"
                v-show="
                  panelFieldDetail['inputSummaryMethod']
                    ? panelFieldDetail.inputSummaryMethod.isShow
                    : false
                "
              ></div>
              <Divider
                v-show="
                  panelFieldDetail['inputSummaryMethod']
                    ? panelFieldDetail.inputSummaryMethod.isShow
                    : false
                "
              />
            </div>
            <!-- v-if="selectedLibData[editingLibIndex][editingLibSubIndex].formatter" -->
            <div
              class="detail-panel-box"
              v-show="
                panelFieldDetail['inputFormat']
                  ? panelFieldDetail.inputFormat.isShow
                  : false
              "
            >
              <o-formatter-setting
                :disabled="
                  panelFieldDetail['inputFormat']
                    ? panelFieldDetail.inputFormat.disabled
                    : true
                "
                v-model="
                  selectedLibData[editingLibIndex][editingLibSubIndex].formatter
                "
                :formatList="formatList[editingLibType]"
              >
              </o-formatter-setting>
              <!-- v-if="
            selectedLibData[editingLibIndex][editingLibSubIndex].formatter
              .type === 'image'
          " -->
              <div
                class="input"
                v-show="
                  panelFieldDetail['inputImgHeight']
                    ? panelFieldDetail.inputImgHeight.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.imgHeight'
                    )
                  }}:
                </span>

                <InputNumber
                  :disabled="
                    panelFieldDetail['inputImgHeight']
                      ? panelFieldDetail.inputImgHeight.disabled
                      : true
                  "
                  :max="500"
                  :min="1"
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .imgHeight
                  "
                  @on-change="saveChanges"
                />
              </div>

              <div class="divider-empty"></div>
              <Divider />
            </div>
          </template>
        </Panel>
        <!-- 字段关联配置————（多对一、下拉选项、辅助属性字段） -->
        <Panel
          v-show="$srv.getx(panelFieldDetail, 'fieldAssociation.isShow', false)"
          name="linkData"
        >
          {{
            $srv.getI18nByPath(
              'oSetupPanel.SetupAttrLibfield.fieldassociationconfiguration'
            )
          }}
          <template #content>
            <div
              class="detail-panel-box"
              v-show="
                panelFieldDetail['inputM2o']
                  ? panelFieldDetail.inputM2o.isShow
                  : false
              "
            >
              <!-- 多对一 -->
              <div class="input">
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.manytoone'
                    )
                  }}:
                </span>

                <o-m2o-editor
                  :disabled="
                    panelFieldDetail['inputM2o']
                      ? panelFieldDetail.inputM2o.disabled === true
                        ? true
                        : !$srv.utils.noValue(
                            selectedLibData[editingLibIndex][editingLibSubIndex]
                              .selectionID
                          )
                      : true
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .many2one
                  "
                  :filter="m2oConfig.filter"
                  :isSetM2o="true"
                  @on-change="m2oChange(editingLibIndex, editingLibSubIndex)"
                >
                </o-m2o-editor>
              </div>

              <div class="divider-empty"></div>
              <Divider />
              <!-- 下拉选项 -->
              <div
                class="input"
                v-show="
                  panelFieldDetail['inputDropDownOptions']
                    ? panelFieldDetail.inputDropDownOptions.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.dropdownoptions'
                    )
                  }}:
                </span>
                <o-m2o-selector
                  :disabled="
                    panelFieldDetail['inputDropDownOptions']
                      ? panelFieldDetail.inputDropDownOptions.disabled === true
                        ? true
                        : !$srv.utils.noValue(
                            selectedLibData[editingLibIndex][editingLibSubIndex]
                              .many2one['toTable']
                          )
                      : true
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .selectionID
                  "
                  :placeholder="
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.dropdownoptions'
                    ) + 'ID'
                  "
                  @model-change="slcChange(editingLibIndex, editingLibSubIndex)"
                  tTable="_sys_property_type"
                  tField="id"
                >
                </o-m2o-selector>
              </div>
              <div class="divider-empty"></div>
              <!-- 联查过滤 -->
              <div class="input">
                <Divider />
                <span> {{ $srv.getI18nByValue('联查过滤') }}: </span>
                <o-m2o-selector
                  :disabled="
                    $srv.utils.noValue(
                      selectedLibData[editingLibIndex][editingLibSubIndex]
                        .selectionID
                    ) &&
                      $srv.utils.noValue(
                        selectedLibData[editingLibIndex][editingLibSubIndex]
                          .many2one.toTable
                      )
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .cascadeFilter
                  "
                  tTable="_sys_publicprocess"
                  tField="f_name"
                  :placeholder="$srv.getI18nByValue('选择公用API')"
                  @on-change="saveChanges"
                >
                </o-m2o-selector>
              </div>

              <div class="divider-empty"></div>
              <Divider />

              <!-- 辅助字段属性 -->
              <!-- 辅助字段属性功能--待开发--保留（现已设置为不可用状态） -->
              <div
                class="input"
                v-if="false"
                v-show="
                  panelFieldDetail['inputAuxiliaryAttributeField']
                    ? panelFieldDetail.inputAuxiliaryAttributeField.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.auxiliaryattributefield'
                    )
                  }}:
                </span>
                <i-input
                  :disabled="
                    panelFieldDetail['inputAuxiliaryAttributeField']
                      ? panelFieldDetail.inputAuxiliaryAttributeField.disabled
                      : true
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex].auxProp
                  "
                  @on-blur="saveChanges"
                >
                </i-input>
              </div>
              <div class="divider-empty"></div>
              <Divider />
            </div>
          </template>
        </Panel>
        <!-- 字段事件 -->
        <Panel
          v-show="$srv.getx(panelFieldDetail, 'fieldEvevts.isShow', false)"
          name="fieldevents"
        >
          {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.fieldevents') }}
          <template #content>
            <div class="detail-panel-box">
              <div
                class="actions"
                v-show="
                  $srv.getx(panelFieldDetail, 'inputEvent.isShow', false, v => {
                    if (
                      v &&
                      !Array.isArray(
                        selectedLibData[editingLibIndex][editingLibSubIndex]
                          .actions
                      )
                    ) {
                      selectedLibData[editingLibIndex][
                        editingLibSubIndex
                      ].actions = [];
                    }
                  })
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.event')
                  }}:
                </span>
                <o-field-event-setting
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex].actions
                  "
                  :copInfo="current"
                  @change="saveChanges"
                ></o-field-event-setting>
              </div>
              <Divider
                v-if="$srv.getx(panelFieldDetail, 'isNodeName.isShow', false)"
              />
              <!-- <div class="divider-empty"></div> -->
              <div
                class="actions-dochange"
                v-if="$srv.getx(panelFieldDetail, 'isNodeName.isShow', false)"
              >
                <i>
                  {{ $srv.getI18nByValue('赋值节点名称') }}
                  :
                </i>
                <iSwitch
                  :disabled="
                    $srv.getx(panelFieldDetail, 'isNodeName.disabled', true)
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .isNodeName
                  "
                  size="small"
                  :true-value="true"
                  :false-value="false"
                  @on-change="saveChanges"
                >
                </iSwitch>
              </div>
              <div class="divider-empty"></div>
              <Divider />
            </div>
          </template>
        </Panel>
        <!-- 子查询 -->
        <Panel
          v-show="$srv.getx(panelFieldDetail, 'fieldSubquery.isShow', false)"
          name="subqueries"
        >
          {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.subqueries') }}
          <template #content>
            <!-- v-if="subqueryShow" -->
            <div
              class="detail-panel-box subquery"
              v-if="
                $srv.getx(panelFieldDetail, 'inputSubQuery.isShow', false) &&
                  current.config.dbType === 'mysql'
              "
            >
              <div class="input">
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.subqueries'
                    )
                  }}:
                </span>
                <Button
                  :disabled="
                    panelFieldDetail['inputSubQuery']
                      ? panelFieldDetail.inputSubQuery.disabled
                      : true
                  "
                  type="primary"
                  size="small"
                  @click="generateSubQuery"
                >
                  <!-- 子查询 -->
                  {{
                    $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.generate')
                  }}
                </Button>
                <div class="subquery-box">
                  <o-m2o-selector
                    :disabled="
                      panelFieldDetail['inputSubQuery']
                        ? panelFieldDetail.inputSubQuery.disabled
                        : true
                    "
                    v-model="sqlSourceTable"
                    :placeholder="
                      $srv.getI18nByPath(
                        'oSetupPanel.SetupAttrLibfield.sourcetable'
                      )
                    "
                    tTable="_sys_fun"
                    tField="title"
                  >
                  </o-m2o-selector>
                  <!-- tField="title" -->
                  <o-m2o-selector
                    :disabled="
                      panelFieldDetail['inputSubQuery']
                        ? panelFieldDetail.inputSubQuery.disabled
                        : true
                    "
                    v-model="sqlSourceField"
                    :placeholder="
                      $srv.getI18nByPath(
                        'oSetupPanel.SetupAttrLibfield.sourcefield'
                      )
                    "
                    tTable="_sys_fun_field"
                    tField="title"
                    :isFunLayout="false"
                    :option="[
                      {
                        title: 'm2o|_sys_fun_id|_sys_fun|title',
                        isShow: true,
                        filter: sqlSourceTable,
                        sort: ''
                      }
                    ]"
                  ></o-m2o-selector>
                  <!-- :isFunLayout="false" -->
                  <!-- :option="[
                      {
                        title: 'm2o|_sys_fun_id|_sys_fun|title',
                        isShow: true,
                        filter: sqlSourceTable,
                        sort: ''
                      }
                    ]" -->
                  <i-input
                    :disabled="
                      panelFieldDetail['inputSubQuery']
                        ? panelFieldDetail.inputSubQuery.disabled
                        : true
                    "
                    v-model="sqlDestField"
                    :placeholder="
                      $srv.getI18nByPath(
                        'oSetupPanel.SetupAttrLibfield.targetfield'
                      )
                    "
                  >
                  </i-input>
                </div>
                <subQueryInput
                  :disabled="
                    panelFieldDetail['inputSubQuery']
                      ? panelFieldDetail.inputSubQuery.disabled
                      : true
                  "
                  :clearable="true"
                  :placeholder="
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.entersubquery'
                    ) + 'SQL'
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .subQuery
                  "
                  @on-clear="saveChanges"
                  @on-blur="
                    strChange(
                      selectedLibData[editingLibIndex][editingLibSubIndex],
                      'subQuery',
                      selectedLibData[editingLibIndex][editingLibSubIndex]
                        .subQuery
                    )
                  "
                />
              </div>
              <div class="divider-empty"></div>
              <Divider />
            </div>
          </template>
        </Panel>

        <!-- 字段过滤与排序————（过滤、排序） -->
        <Panel
          v-show="
            $srv.getx(
              panelFieldDetail,
              'FieldFilteringAndSorting.isShow',
              false
            )
          "
          name="filterAndSort"
        >
          {{
            $srv.getI18nByPath(
              'oSetupPanel.SetupAttrLibfield.fieldfilteringandsorting'
            )
          }}
          <template #content>
            <div
              class="detail-panel-box"
              v-show="
                panelFieldDetail['inputInitFilter']
                  ? panelFieldDetail.inputInitFilter.isShow
                  : false
              "
            >
              <div class="input">
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.initialfilter'
                    )
                  }}:</span
                >
                <i-input
                  :disabled="
                    panelFieldDetail['inputInitFilter']
                      ? panelFieldDetail.inputInitFilter.disabled
                      : true
                  "
                  :clearable="true"
                  :placeholder="
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.enterfiltercriteria'
                    )
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .initFilter
                  "
                  @on-clear="saveChanges"
                  @on-blur="saveChanges"
                >
                </i-input>
              </div>
            </div>
            <div
              class="detail-panel-box"
              v-show="
                panelFieldDetail['inputDefFilter']
                  ? panelFieldDetail.inputDefFilter.isShow
                  : false
              "
            >
              <div class="input">
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.defaultfiltering'
                    )
                  }}:
                </span>
                <i-input
                  :disabled="
                    panelFieldDetail['inputDefFilter']
                      ? panelFieldDetail.inputDefFilter.disabled
                      : true
                  "
                  :clearable="true"
                  :placeholder="
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.enterfiltercriteria'
                    )
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex].filter
                  "
                  @on-clear="saveChanges"
                  @on-blur="saveChanges"
                >
                </i-input>
              </div>
            </div>
            <div class="detail-panel-box">
              <div
                class="select"
                v-show="
                  panelFieldDetail['inputInitSort']
                    ? panelFieldDetail.inputInitSort.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.initialsort'
                    )
                  }}:</span
                >
                <Select
                  :disabled="
                    panelFieldDetail['inputInitSort']
                      ? panelFieldDetail.inputInitSort.disabled
                      : true
                  "
                  clearable
                  transfer
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .initSort
                  "
                  @on-change="saveChanges"
                >
                  <Option value="desc">
                    {{
                      $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.desc')
                    }}
                  </Option>
                  <Option value="asc">
                    {{
                      $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.asc')
                    }}
                  </Option>
                </Select>
              </div>
              <div
                class="input"
                v-show="
                  panelFieldDetail['inputInitsortWeights']
                    ? panelFieldDetail.inputInitsortWeights.isShow
                    : false
                "
              >
                <span>
                  {{
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.initializesortweights'
                    )
                  }}:
                </span>
                <InputNumber
                  :disabled="
                    panelFieldDetail['inputInitsortWeights']
                      ? panelFieldDetail.inputInitsortWeights.disabled
                      : true
                  "
                  :clearable="true"
                  type="number"
                  :placeholder="
                    $srv.getI18nByPath(
                      'oSetupPanel.SetupAttrLibfield.sortweights'
                    )
                  "
                  v-model="
                    selectedLibData[editingLibIndex][editingLibSubIndex]
                      .initSortWeight
                  "
                  @on-change="saveChanges"
                  @on-blur="saveChanges"
                >
                </InputNumber>
              </div>
              <div class="divider-empty"></div>
            </div>
          </template>
        </Panel>
      </Collapse>
    </div>
  </div>
</template>
<script lang="ts">
import oChartSetting from '@/components/piece/o-chart-setting.vue';
import oFieldEventSetting from '@/components/piece/o-field-event-setting.vue';
import oFormatterSetting from '@/components/piece/o-formatter-setting.vue';
import oHeaderGroupSetting from '@/components/piece/o-header-group-setting.vue';
import oRulesSetting from '@/components/piece/o-rules-setting.vue';
import { T_basePanel, T_baseView, T_refBaseGrid } from './command/comps/types';
import {
  I_command,
  N_oSetupPanel,
  T_srv,
  Tsrv,
  auditDefaultFields,
  ifs,
  recordsDefaultFields,
  ts,
  vue
} from './config';
import cTable from './cTable.vue';
import fieldIntroductionSetting from './settingItems/field-introduction-setting.vue';
import subQueryInput from './subQueryInput.vue';

@T_srv.comp({
  components: {
    oHeaderGroupSetting,
    oFieldEventSetting,
    oRulesSetting,
    oChartSetting,
    oFormatterSetting,
    cTable,
    subQueryInput,
    fieldIntroductionSetting
  }
})
export default class SetupAttrLibfield extends vue {
  @T_srv.prop() isChange!: boolean;

  @T_srv.prop() tabChange: any;

  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  private tableData: object = {};

  /* 组件名 */
  private G_compName: string = 'SetupAttrLibField';

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  private current: any = null;

  private cellID: string | undefined = '';

  /* 基本控制 */
  private detailPanelStyle = {};

  // 打开关闭字段详情
  // private btnDisable: any = [];

  // btn是否禁用
  private activeGroup: number | undefined = 0;

  // 当前激活的分组
  private isTreeGridNavMode = false;

  private detailSelectionID: number | null = null;

  private uniqueIndexes: any = {};

  // 唯一索引
  private indexes: any = {};

  // 索引
  private rules: any = {};

  private headerGroup: any = {};

  private charts: any = {};

  // 当前字段信息
  private editingLibIndex: string | null = null;

  // 当前表的编号
  private editingLibSubIndex: number | null = null;

  // 表字段的编号
  private editingLibType: string = '';

  // 当前字段的format类型
  private editingLibSpeType: string = ''; // 当前字段的详细类型

  private allTablesLoading = false;

  private m2oOptions: any = [];

  // many2one所有的对方表
  private m2oOptionsCache: any = [];

  private sqlSourceTable = '';

  private sqlSourceField = '';

  private sqlDestField = '';

  private GT_command: I_command = null;

  // 引用表模式
  public isRefBaseGridMode: boolean = false;

  // refBaseGrid用
  public refTable: string = '';

  private eleRefMap = new Map<string, string>();

  // private detailPanelName: Array<string> = ['fieldProperties'];
  private detailPanelName: Array<string> = [
    'fieldProperties',
    'dataFormat',
    'linkData',
    'eventAndQuery',
    'fieldevents',
    'subqueries',
    'filterAndSort'
  ];

  // formatter的选项
  private formatList = {
    number: [
      {
        value: 'number',
        label: Tsrv.getI18nByPath('piece.oChartSetting.number')
      },
      {
        value: 'currency',
        label: Tsrv.getI18nByPath('piece.oChartSetting.currency')
      },
      {
        value: 'percent',
        label: Tsrv.getI18nByPath('piece.oChartSetting.percent')
      }
    ],
    text: [
      {
        value: 'i18n',
        label: Tsrv.getI18nByPath('piece.oChartSetting.i18n')
      },
      {
        value: 'file',
        label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.file')
      },
      {
        value: 'icon',
        label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.icon')
      },
      {
        value: 'image',
        label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.image')
      },
      {
        value: 'color',
        label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.color')
      },
      {
        value: 'richText',
        label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.richText')
      },
      {
        value: 'control',
        label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.control')
      }
    ],
    json: [
      {
        value: 'image',
        label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.image')
      },
      {
        value: 'file',
        label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.file')
      },
      {
        value: 'control',
        label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.control')
      }
    ]
  };

  // 货币种类
  private currencyList = [
    {
      value: '¥',
      label: '¥'
    },
    {
      value: '$',
      label: '$'
    },
    {
      value: 'US$',
      label: 'US$'
    }
  ];

  public sourceTable = '';

  private sourceTableID = null;

  private sourceDeleteDisable = true;

  // 表字段（导航）
  private sourceMainColumn = [
    {
      type: 'selection',
      width: 34,
      align: 'center'
    },
    {
      title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.fieldname'),
      key: 'field',
      align: 'center'
    },
    {
      title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.locallanguage'),
      key: 'field',
      align: 'center',
      render: (h: any, params: any) => {
        return h('span', Tsrv.getI18nBySrv(params.row['field']));
      }
    },
    {
      title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.mainsection'),
      key: 'keyField',
      width: 30,
      align: 'center',
      slot: 'keyField'
    },
    {
      title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.childstage'),
      key: 'childField',
      width: 30,
      align: 'center',
      slot: 'childField'
    },
    {
      title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.show'),
      key: 'isShow',
      width: 30,
      align: 'center',
      slot: 'isShow'
    },
    {
      title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.filter'),
      key: 'filter',
      width: 60,
      align: 'center',
      slot: 'filter'
    }
  ];

  // 表尾规则
  private footerMethodList = [
    {
      value: 0,
      label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.total')
    },
    {
      value: 1,
      label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.averagevalue')
    },
    {
      value: 2,
      label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.max')
    },
    {
      value: 3,
      label: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.min')
    }
  ];

  // 表字段
  private selectedLibColumn = [
    {
      type: 'selection',
      width: 34,
      align: 'center'
    },
    {
      title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.fieldname'),
      key: 'field',
      align: 'center'
    },
    {
      title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.locallanguage'),
      key: 'field',
      align: 'center',
      render: (h: any, params: any) => {
        return h('span', Tsrv.getI18nBySrv(params.row['field']));
      }
    },
    {
      title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.type'),
      key: 'type',
      align: 'center'
    }
  ];

  private selectedLib: any = [];

  // 已选择lib
  selectedLibData: any = {};

  // 当前字典面板内要展示各项
  private panelItems: any = {};

  // 字段明细面板配置
  private panelFieldDetail: any = {};

  // 树表来源表类型
  private sourceTableType: N_oSetupPanel.N_comps.TABLE_TYPE;

  // 当功能是单据时,记录已有的表体
  private panelTabelName: Array<string> = [];

  // 多对一字段设置配置
  private m2oConfig: any = {
    filter: new ts.T_filter()
  };

  get subqueryShow() {
    const sub: any = this.selectedLibData[this.editingLibIndex][
      this.editingLibSubIndex
    ].footerMethod;

    return !Tsrv.utils.isNumber(sub);
  }

  /**
   * 获取当前组件的类
   */
  get currentCompClass() {
    const compClass = this.GT_command.Tsetup.getCompClass(
      this.GT_command.Tsetup?.component?.current?.name
    );
    if (compClass instanceof T_refBaseGrid) {
      this.isRefBaseGridMode = true;
    } else {
      this.isRefBaseGridMode = false;
    }
    return compClass;
  }

  @T_srv.watch('isChange')
  private componentChanged(val?: boolean) {
    this.current = this.GT_command.Tsetup.component.current;
    this.refTable = this.current.config?.refTable ?? '';
    this.cellID = this.GT_command.Tsetup.cell.id;
    this.releaseFromConfig();
    this.hideDetailPanel();
  }

  @T_srv.watch('tabChange')
  private tabsChanged(Val?: string) {
    if (Val === 'attr_2') {
      this.current = this.GT_command.Tsetup.component.current;
      this.cellID = this.GT_command.Tsetup.cell.id;
      this.releaseFromConfig();
      this.hideDetailPanel();
    }
  }

  created() {
    this.G_compID = Tsrv.utils.getGUID();
    /* 如果外部有传入组件信息 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox = new ts.T_compBox(this.G_compID); // 使用本地实例
    } else {
      this.G_compID = this.compBoxInfo.compID;
      this.GT_compBox = this.compBoxInfo.TcompBox;
    }
    this.GT_compBoxInfo = { compID: this.G_compID, TcompBox: this.GT_compBox };
    this.GT_command = this.GT_compBox.getCompMergeName(
      this.G_compID,
      'oSetupPanelCMD'
    );
    this.init();
  }

  mounted() {
    this.componentChanged();
    /* 向父组件发送实例 */
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
  }

  setEleRef(eleName: string, refName: string) {
    this.eleRefMap.set(eleName, refName);
  }

  getEleRef(eleName: string): any {
    const ref = this.$refs[this.eleRefMap.get(eleName)];
    return ref ? ref[0] : null;
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 最终应用组件销毁 */
    /* this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName,'funName'); */

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }

  beforeDestroy() {
    this.$bus.$off('magic-setup-source');
    this.$bus.$off('magic-setup-source-field');
    this.$bus.$off('magic-setup-lib');
  }

  private init() {
    this.m2oConfig.filter.filter = { table_type: { $eq: 0 } };
    this.getPanelTableName();
  }

  private refreshTableData(
    state: 'add' | 'delete' | 'reload',
    data: N_oSetupPanel.I_tableData
  ) {
    for (const key in data) {
      const n = key.split('_');
      if (Tsrv.utils.noValue(n) && n.length !== 3) {
        continue;
      }

      if (Tsrv.utils.noValue(this.tableData[key]) || state === 'reload') {
        this.tableData[key] = [];
      }
      if (state === 'add' || state === 'reload') {
        data[key].forEach(el => {
          if (
            this.tableData[key].findIndex(item => item.field === el.field) ===
            -1
          ) {
            this.tableData[key].push(Tsrv.utils.clone(el));
          }
        });
      } else {
        this.tableData[key] = [];
        data[key].forEach(el => {
          this.tableData[key].push(Tsrv.utils.clone(el));
        });
      }
      const cTableRef = this.getEleRef(`libTbl${n[1]}${n[2]}`);
      if (!Tsrv.utils.noValue(cTableRef)) {
        cTableRef.loadData(this.tableData[key]);
      }
    }
  }

  private handleRowClick(row, index) {
    this.showDetailPanel({
      row,
      index
    });
  }

  private generateSubQuery() {
    let currentTable = '';
    for (let i = 0; i < this.selectedLib.length; i++) {
      const find = Tsrv.utils.find(
        this.selectedLib[i].content,
        el => el.list === this.editingLibIndex
      );
      if (find) {
        if (
          this.selectedLib[i].title ===
          Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.header')
        ) {
          currentTable = this.current.config.name;
        } else {
          currentTable = this.selectedLib[i].title;
        }
        break;
      }
    }
    if (currentTable === '') currentTable = this.current.config.name;
    this.$set(
      this.selectedLibData[this.editingLibIndex][this.editingLibSubIndex],
      'subQuery',
      `select ${this.sqlSourceField} from ${this.sqlSourceTable} where id = ${currentTable}.${this.sqlDestField} limit 1`
    );
    this.saveChanges();
  }

  /**
   * 表选择框变化（导航）
   */
  private sourceSelectChange() {
    const tableEle: any = this.$refs.sourceMainTbl;
    const table = Tsrv.utils.isArray(tableEle) ? tableEle[0] : tableEle;
    const selection = table.getSelection();
    this.sourceDeleteDisable = selection.length === 0;
  }

  /**
   * 移除来源表（导航）
   */
  private sourceDelete() {
    const tableEle: any = this.$refs.sourceMainTbl;
    const table = Tsrv.utils.isArray(tableEle) ? tableEle[0] : tableEle;
    const selection = table.getSelection();
    selection.forEach((el: any) => {
      Tsrv.utils.remove(
        this.current.config['tableDataSource'].main.fields,
        item => item.field === el.field
      );
    });
    this.sourceSelectChange();
    this.saveChanges();
  }

  /**
   * 来源表主段选择（导航）
   */
  private selectSourceKeyField(index: number) {
    this.current.config.tableDataSource.main.fields.forEach(
      (el: any, idx: number) => {
        el.keyField = idx === index;
      }
    );
    this.saveChanges();
  }

  /**
   * 来源表子段选择（导航）
   */
  private selectSourceChildField(index: number, e: boolean) {
    if (e) {
      this.current.config.tableDataSource.main.fields.forEach(
        (el: any, idx: number) => {
          el.childField = idx === index;
        }
      );
    }
    this.saveChanges();
  }

  /**
   * 来选表选择是否显示（导航）
   */
  private selectSourceIsShow(index: number, e: boolean) {
    if (!e) {
      this.current.config.tableDataSource.main.fields[index].keyField = false;
    }
    this.saveChanges();
  }

  /**
   * 选择来源表（导航）
   */
  private selectSourceTable() {
    Tsrv.utils
      .createModal('oMagicBox', {
        source: { funid: 1, field: '_sys_fun', limit: 1 },
        config: null
      })
      .then(data => {
        if (data !== null && data.length > 0) {
          if (data[0].title) {
            this.sourceTable = data[0].title;
            this.sourceTableID = data[0].id;
            this.current.config['tableDataSource'].main.name = data[0].title;
            this.current.config['tableDataSource'].main.id = data[0].id;
            this.sourceTableType = data[0].table_type;
            this.saveChanges();
          }
        }
      });
  }

  /**
   * 来源表字段选择（导航）
   */
  private selectSourceTableFields() {
    switch (this.sourceTableType) {
      case 0:
        this.selectFieldsByBasegrid();
        break;
      case 1:
        this.selectFieldsByBaseview();
        break;
      default:
        throw new Error('虚拟表无法选择来源字段');
    }
  }

  private selectFieldsByBasegrid() {
    Tsrv.utils
      .createModal('oMagicBox', {
        source: {
          funid: 1,
          field: '_sys_fun_field',
          limit: 99,
          filter: {
            initSearch: { field: '_sys_fun_id', value: this.sourceTableID }
          }
        },
        config: null
      })
      .then(data => {
        if (data !== null && data.length > 0) {
          if (data !== null && data.length > 0) {
            this.sourceDataAdd(data);
          }
        }
      });
  }

  private selectFieldsByBaseview() {
    const params = {
      dbType: Tsrv.globalVar.dbType.MYSQL,
      viewName: this.sourceTable
    };
    Tsrv.standardPostReq<ifs.I_setDataRes, any>(params, Tsrv.url.getView).then(
      ([res, msg]) => {
        this.$msg(msg ?? res.msg);
        // let data: Array<{ colName: string; dataType: string }> = [];
        if (res.success) {
          if (Tsrv.utils.noValue(res.data)) {
            this.$msg(Tsrv.getI18nByValue('未返回数据'));
          } else {
            this.sourceDataAdd(res.data);
          }
        }
      }
    );
  }

  /**
   * 增加表数据（导航）
   */
  private sourceDataAdd(data: any) {
    const selected = Tsrv.utils.map<any, unknown, unknown>(
      this.current.config['tableDataSource'].main.fields,
      el => el.field
    );
    data.forEach((el: any) => {
      if (selected.indexOf(el.title) < 0) {
        this.current.config['tableDataSource'].main.fields.push({
          field: el.title ?? el.colName,
          keyField: false,
          childField: false,
          isShow: true,
          filter: ''
        });
      }
    });
    this.saveChanges();
  }

  /**
   * 选取字段
   */
  private selectFieldForTable(index: number, subIndex: number) {
    Tsrv.utils
      .createModal('oMagicBox', {
        source: {
          funid: 4,
          field: '_sys_libfield',
          limit: 99
        },
        config: null
      })
      .then(data => {
        if (data !== null && data.length > 0) {
          this.addFieldsToTable(data, index, subIndex);
        }
      });
  }

  /**
   * 添加字段（从magicbox获取数据，处理数据）
   */
  private addFieldsToTable(data: any, index: number, subIndex: number) {
    // 如果返回数据是以个数组
    if (Tsrv.utils.isArray(data)) {
      // 获取当前表的字段，防止重复加入
      const selectedArr: string[] = [];
      const currentTableName = this.selectedLib[index].content[subIndex].list;
      this.selectedLib[index].content.forEach((el: any) => {
        const listName = el.list;
        this.selectedLibData[listName].forEach((el2: any) => {
          selectedArr.push(el2.field);
        });
      });
      // 添加字段
      data.forEach((el: any) => {
        if (selectedArr.indexOf(el.title) < 0) {
          const lData = {
            fieldID: el.id,
            field: el.title,
            type: el.data_type,
            isShow: true,
            notNull: false,
            defValue: '',
            fieldPrefix: {
              icon: '',
              iconStatus: '',
              content: ''
            },
            fieldSuffix: {
              icon: '',
              iconStatus: '',
              content: ''
            },
            placeholder: '',
            comment: '',
            selectionID: null,
            disabled: false,
            defaultFilter: false,
            fixedLeft: false,
            fixedRight: false,
            nodeData: false,
            footerMethod: null,
            formatter: {
              type: '',
              decimal: 0,
              thousandmark: false,
              currency: ''
            },
            // actions: {
            //   dochange: ''
            // },
            actions: [],
            cascadeFilter: '', // 联查过滤
            auxProp: '',
            minWidth: '',
            appWeight: '',
            isDes: false,
            many2one: '',
            align: 'left',
            subQuery: ''
          };
          if (this.current.name.toLowerCase() === 'graph') {
            lData['isNodeName'] = false;
          }
          this.selectedLibData[currentTableName].push(lData);
        } else {
          this.$msg(
            `${el.title} - ${Tsrv.getI18nByPath(
              'oSetupPanel.SetupAttrLibfield.fieldalreadyexists'
            )}`
          );
        }
      });
      this.refreshTableData('add', this.selectedLibData);
      this.saveChanges();
    }
  }

  // 移动连续行
  private moveContinuousRows(
    rowIndexes: Array<number>
  ): Array<{ start: number; end: number }> {
    rowIndexes.sort((a, b) => a - b);
    const continuousRanges = [];
    let currentRangeStart = null;
    for (let i = 0; i < rowIndexes.length; i++) {
      // 如果是连续行
      if (i > 0 && rowIndexes[i] - rowIndexes[i - 1] === 1) {
        // 并且还没有开始记录当前连续段，则开始记录
        if (currentRangeStart === null) {
          currentRangeStart = rowIndexes[i - 1];
        }
      } else {
        // 如果不是连续行，并且已经记录了当前连续段，则将其添加到结果中
        if (currentRangeStart !== null) {
          continuousRanges.push({
            start: currentRangeStart,
            end: rowIndexes[i - 1]
          });
          // 开启下一个连续行循环
          currentRangeStart = null;
        }
      }
      // 如果是最后一个索引，并且他属于连续段
      if (i === rowIndexes.length - 1 && currentRangeStart !== null) {
        continuousRanges.push({ start: currentRangeStart, end: rowIndexes[i] });
      }
    }
    return continuousRanges;
  }

  private moveRows(
    data: Array<any>,
    rowIndexes: Array<number>,
    direction: 'up' | 'down'
  ) {
    const movedData = [...data];
    const moveDataLength = movedData.length;
    // 处理特殊情况，选择的行存在连续行
    const continuousRows = this.moveContinuousRows(rowIndexes);
    if (continuousRows.length > 0) {
      continuousRows.forEach(range => {
        // 裁剪掉连续的选中行索引
        const rowStart = rowIndexes.indexOf(range.start);
        const rowEnd = rowIndexes.indexOf(range.end);
        rowIndexes.splice(rowStart, rowEnd - rowStart + 1);
        // 处理连续行
        if (direction === 'up' && range.start !== 0) {
          const temp = movedData.splice(
            range.start,
            range.end - range.start + 1
          );
          movedData.splice(range.start - 1, 0, ...temp);
        } else if (direction === 'down' && range.end !== moveDataLength - 1) {
          const temp = movedData.splice(
            range.start,
            range.end - range.start + 1
          );

          movedData.splice(range.end, 0, ...temp);
        }
      });
    }
    if (continuousRows.length === 0 || rowIndexes.length > 0) {
      // 处理非连续行
      for (let i = 0; i < rowIndexes.length; i++) {
        const rowIndex: number = rowIndexes[i];

        if (direction === 'up') {
          if (rowIndex === 0) {
            continue; // 不做处理
          }
          const temp = movedData[rowIndex - 1];
          movedData[rowIndex - 1] = movedData[rowIndex];
          movedData[rowIndex] = temp;
        } else if (direction === 'down') {
          if (rowIndex === movedData.length - 1) {
            continue;
            // 不做处理;
          }
          const temp = movedData[rowIndex + 1];
          movedData[rowIndex + 1] = movedData[rowIndex];
          movedData[rowIndex] = temp;
        }
      }
    }

    return movedData;
  }

  /**
   * 移动字段
   */
  private moveFields(
    index: number,
    subIndex: number,
    name: 'btnLibUp' | 'btnLibDown'
  ) {
    const key = `mark_${index}_${subIndex}`;

    const refCtable = this.getEleRef(`libTbl${index}${subIndex}`);
    const selection = refCtable.refTable.getSelection();
    const total: number = this.tableData[key] ? this.tableData[key].length : 0;
    if (Tsrv.utils.noValue(selection) || selection.length === total) {
      return;
    }
    const rowIdxs: Array<number> = [];
    const rowField: Array<string> = [];

    selection.forEach(v => {
      const idx = this.tableData[key].findIndex(el => el.field === v.field);
      if (idx > -1) {
        rowIdxs.push(idx);
        rowField.push(v.field);
      }
    });
    this.selectedLibData[key].splice(0); // 清空保留原指针
    if (name === 'btnLibUp') {
      this.selectedLibData[key].push(
        ...this.moveRows(this.tableData[key], rowIdxs, 'up')
      );
    } else {
      this.selectedLibData[key].push(
        ...this.moveRows(this.tableData[key], rowIdxs, 'down')
      );
    }

    this.refreshTableData('reload', this.selectedLibData);
    rowField.forEach(field => {
      const idx = this.tableData[key].findIndex(el => el.field === field);
      if (idx > -1) {
        setTimeout(() => {
          refCtable.refTable.toggleSelect(idx);
        }, 100);
      }
    });
    this.saveChanges();
  }

  // 删除字段前
  private beforeRemoveFieldsFromTable(
    index: number,
    subIndex: number,
    basePanelFunName: string = null
  ) {
    if (
      Tsrv.utils.noValue(
        this.GT_compBox.getCompMergeName(this.G_compID, 'oSetupPanel').config
      )
    ) {
      this.removeFieldsFromTable(index, subIndex);
      return;
    }
    if (
      !Tsrv.utils.noValue(basePanelFunName) &&
      this.panelTabelName.indexOf(basePanelFunName) < 0
    ) {
      this.removeFieldsFromTable(index, subIndex);
      return;
    }

    const refCtable = this.getEleRef(`libTbl${index}${subIndex}`);
    const selection = refCtable.refTable.getSelection();
    const fields: Array<string> = [];
    // 检查字段所涉及的视图
    selection.forEach((select: any) => {
      if (Tsrv.utils.noValue(select?.subQuery)) {
        fields.push(select.field);
      }
    });
    const filter = {};
    if (fields.length > 0) {
      Promise.all(
        fields.map(item => {
          let funName = this.current.config.name;
          if (this.currentCompClass instanceof T_basePanel) {
            if (index > 0) {
              funName = basePanelFunName || null;
            }
          }
          const gpfd: ts.T_GPFD = new ts.T_GPFD();
          gpfd.setLang(this.$i18n.locale || 'en_US');
          gpfd.setGlobalSerach('').setFunName(funName);
          gpfd.setFilter(filter).setSort(null);
          gpfd.setDbType(Tsrv.globalVar.dbType.MYSQL);
          gpfd.setAgreedFields(item);
          gpfd.setIsDistinct(true);
          return Tsrv.getData<any, ifs.I_GPFD>(gpfd);
        })
      ).then(rs => {
        rs.forEach(r => {
          const [b, res, rows, msg] = r;
          if (!b && msg) {
            // this.$msg(msg ?? res.msg);
            this.removeFieldsFromTable(index, subIndex);
          } else {
            if (!Tsrv.utils.noValue(rows)) {
              this.$Modal.confirm({
                title: Tsrv.getI18nByPath('prompt.isDelete') as string,
                content: Tsrv.getI18nByPath(
                  'prompt.deleteFieldsData'
                ) as string,
                onOk: () => {
                  this.removeFieldsFromTable(index, subIndex);
                }
              });
            } else {
              this.removeFieldsFromTable(index, subIndex);
            }
          }
        });
      });
    } else {
      this.removeFieldsFromTable(index, subIndex);
    }
  }

  /**
   * 删除字段
   */
  private removeFieldsFromTable(index: number, subIndex: number) {
    // 获取当前表的实例
    const refCtable = this.getEleRef(`libTbl${index}${subIndex}`);
    const selection = refCtable.refTable.getSelection();
    const fields: Array<string> = [];
    // 检查字段所涉及的视图
    selection.forEach((select: any) => {
      fields.push(select.field);
    });
    this.chkViewByFunField(
      index,
      subIndex,
      this.current.config.name,
      fields
    ).then(b => {
      if (b) {
        this.doRemoveFieldsFromTable(index, subIndex);
      }
    });
  }

  private doRemoveFieldsFromTable(index: number, subIndex: number) {
    // 获取当前表的实例
    const refCtable = this.getEleRef(`libTbl${index}${subIndex}`);
    const selection = refCtable.refTable.getSelection();

    selection.forEach((select: any) => {
      // 删除数据
      this.selectedLibData[`mark_${index}_${subIndex}`].forEach(
        (el: any, idx: number) => {
          if (el.field === select.field) {
            this.selectedLibData[`mark_${index}_${subIndex}`].splice(idx, 1);
          }
        }
      );
      // 修改index
      const uniqueIndexesLength = Tsrv.utils.clone(
        this.uniqueIndexes[`mark_${index}`],
        true
      ).length;
      const indexesLength = Tsrv.utils.clone(
        this.indexes[`mark_${index}`],
        true
      ).length;
      if (uniqueIndexesLength > 0) {
        for (let uniqIdx = 0; uniqIdx < uniqueIndexesLength; uniqIdx++) {
          this.uniqueIndexes[`mark_${index}`].forEach(
            (el: any, idx: number) => {
              el.forEach((item: any) => {
                if (item.name === select.field) {
                  this.uniqueIndexes[`mark_${index}`].splice(idx, 1);
                }
              });
            }
          );
        }
      }
      if (indexesLength > 0) {
        for (let idxIdx = 0; idxIdx < indexesLength; idxIdx++) {
          this.indexes[`mark_${index}`].forEach((el: any, idx: number) => {
            el.forEach((item: any) => {
              if (item.name === select.field) {
                this.indexes[`mark_${index}`].splice(idx, 1);
              }
            });
          });
        }
      }
    });
    this.refreshTableData('delete', this.selectedLibData);
    this.saveChanges();
  }

  private async chkViewByFunField(
    index: number,
    subIndex: number,
    funName: string,
    fields: string[]
  ): Promise<boolean> {
    const [r, err] = await Tsrv.standardPostReq<ifs.I_queryRes<any>, any>(
      { funName, fields },
      Tsrv.url.getViewByTableField
    );
    if (Tsrv.utils.noValue(funName)) {
      return true;
    }
    if (err || !r.success) {
      this.$msg(err ?? r.msg);
    } else {
      if (r.data.total > 0) {
        const vs: Array<string> = [];
        r.data.rows.forEach(el => {
          vs.push(el.viewName);
        });
        const content = `${Tsrv.getI18nByValue(
          '删除字段有可能影响到视图不能正常工作:'
        )}${vs.join(',')}`;
        const s = await Tsrv.dialog.confirm(
          content,
          Tsrv.getI18nByValue('警告'),
          { zIndex: 9999 }
        );
        return s === 'confirm';
      }
    }

    return true;
  }

  /**
   * 选择字段变化
   */
  private tableSelectionChange(
    index: number,
    subIndex: number,
    eleName: string,
    e
  ) {
    const selection = e.currentRow;
    const copy = Tsrv.utils.clone(this.panelItems, true);
    if (selection.length > 0) {
      this.setTableBtnDisabled(copy, 'all', false);
    } else {
      this.setTableBtnDisabled(copy, 'all', true);
    }
  }

  private setTableBtnDisabled(
    content: object,
    status: 'all' | 'set',
    val: Array<{ name: string; val: boolean }> | boolean
  ) {
    if (typeof val === 'boolean') {
      if (status === 'all') {
        Object.keys(content).forEach(k => {
          if (k.startsWith('btn') && k !== 'btnSelect' && k !== 'btnGetField') {
            this.$set(this.panelItems[k], `disabled`, val);
          }
        });
      }
    } else if (Array.isArray(val)) {
      if (status === 'set') {
        val.forEach(v => {
          Object.keys(content).forEach(k => {
            if (k === v.name) {
              this.$set(this.panelItems[k], `disabled`, val);
            }
          });
        });
      }
    }
  }

  /**
   * 添加索引
   */
  private addIndex(index: number, type: string) {
    let subIndex = 0;
    let selectionArr: Array<any> = [];
    // 遍历获取当前分组所有表选则
    while (this.getEleRef(`libTbl${index}${subIndex}`)) {
      const refCtable = this.getEleRef(`libTbl${index}${subIndex}`);
      const selection = refCtable.refTable.getSelection();
      selectionArr = selectionArr.concat(selection);
      refCtable.refTable.selectAll(false);
      subIndex++;
    }
    // 去重（防止重复）
    selectionArr = Tsrv.utils.uniq(selectionArr);

    if (selectionArr.length >= 0) {
      const indexes: any = [];
      // 组装显示表
      selectionArr.forEach((el: any) => {
        indexes.push({
          id: el.fieldID,
          name: el.field
        });
      });
      // 更新数据
      if (type === 'uniqIndex') {
        if (this.indexIsRepeat(this.uniqueIndexes[`mark_${index}`], indexes)) {
          this.$Message.warning(
            Tsrv.getI18nByPath('warm.duplicateIndex') as string
          );
        } else {
          this.uniqueIndexes[`mark_${index}`].push(indexes);
        }
      } else if (type === 'index') {
        if (this.indexIsRepeat(this.indexes[`mark_${index}`], indexes)) {
          this.$Message.warning(
            Tsrv.getI18nByPath('warm.duplicateIndex') as string
          );
        } else {
          this.indexes[`mark_${index}`].push(indexes);
        }
      }
      // if (type === 'uniqIndex') {
      //   this.uniqueIndexes[`mark_${index}`].push(indexes);
      // } else if (type === 'index') {
      //   this.indexes[`mark_${index}`].push(indexes);
      // }
      this.saveChanges();
    }
  }

  /**
   * 判断索引是否重复
   */
  private indexIsRepeat(allArr: Array<any>, arr: Array<any>): boolean {
    if (allArr.length > 0) {
      const targetArr = [];
      allArr.forEach((el: any) => {
        if (el.length === arr.length) {
          targetArr.push(el);
        }
      });
      if (Tsrv.utils.noValue(targetArr)) {
        return false;
      }
      return (
        Tsrv.utils.findKey(
          targetArr,
          item =>
            Tsrv.utils.md5(JSON.stringify(item)) ===
            Tsrv.utils.md5(JSON.stringify(arr))
        ) > -1
      );
    }
    return false;
  }

  /**
   * 移除索引前
   */
  private beforeRemoveIndex(index: number, subIndex: number, type: string) {
    const magContent =
      type === 'uniqIndex'
        ? 'prompt.deleteUniqIndex'
        : type === 'index'
        ? 'prompt.deleteIndex'
        : 'prompt.isExecute';
    this.$Modal.confirm({
      title: Tsrv.getI18nByPath('prompt.isDelete') as string,
      content: Tsrv.getI18nByPath(magContent) as string,
      onOk: () => {
        this.removeIndex(index, subIndex, type);
      }
    });
  }

  /**
   * 移除索引
   */
  private removeIndex(index: number, subIndex: number, type: string) {
    if (type === 'uniqIndex') {
      this.uniqueIndexes[`mark_${index}`].splice(subIndex, 1);
    } else if (type === 'index') {
      this.indexes[`mark_${index}`].splice(subIndex, 1);
    }
    this.saveChanges();
  }

  /**
   * 描述字段切换
   */
  private isDesChange(val: boolean) {
    if (val === true) {
      if (
        this.activeGroup !== undefined &&
        this.editingLibIndex !== null &&
        this.editingLibSubIndex !== null
      ) {
        const index = this.activeGroup;
        let subIndex = 0;
        while (this.selectedLibData[`mark_${index}_${subIndex}`]) {
          const data = this.selectedLibData[`mark_${index}_${subIndex}`];
          data.forEach((el: any) => {
            el.isDes = false;
          });
          subIndex++;
        }
        this.selectedLibData[this.editingLibIndex][
          this.editingLibSubIndex
        ].isDes = true;
        this.selectedLibData[this.editingLibIndex][
          this.editingLibSubIndex
        ].notNull = true;
      }
      this.saveChanges();
    }
  }

  /**
   * 节点数据切换
   */
  private isNodeDataChange(val: boolean) {
    const currTableColumn = this.selectedLibData[this.editingLibIndex];
    if (
      this.GT_command.Tsetup.component.current.name !==
      N_oSetupPanel.N_comps.COMP_NAME.GRAPH
    ) {
      return;
    }
    if (!this.GT_command.Tsetup.component.current.config?.nodeColumn) {
      this.GT_command.Tsetup.component.current.config['nodeColumns'] = [];
    }
    const tableNodeColumns = this.GT_command.Tsetup.component.current.config[
      'nodeColumns'
    ];
    const selRowData = this.selectedLibData[this.editingLibIndex][
      this.editingLibSubIndex
    ];
    if (val) {
      if (
        // this.selectedLibDataRetained
        tableNodeColumns.findIndex(el => el.field === selRowData.field) === -1
      ) {
        // this.selectedLibDataRetained.push(selRowData);
        tableNodeColumns.push(selRowData);
        // this.selectedLibData[this.editingLibIndex][
        //   this.editingLibSubIndex
        // ] = this.selectedLibDataRetained;
        // currTableColumn.forEach((v, idx, arr) => {
        //   if (v.field === selRowData.field) {
        //     arr.splice(idx);
        //   }
        // });
      }
    } else {
      // this.selectedLibDataRetained.forEach((v, idx, arr) => {
      tableNodeColumns.forEach((v, idx, arr) => {
        if (v.field === selRowData.field) {
          arr.splice(idx);
        }
      });
      // if (
      //   currTableColumn.findIndex(el => el.field === selRowData.field) === -1
      // ) {
      //   currTableColumn.push(selRowData);
      // }
    }
    this.saveChanges();
  }

  /**
   * 配置 => 实例
   */
  private releaseFromConfig() {
    const baseGrid = N_oSetupPanel.N_comps.COMP_NAME.BASE_GRID;
    const basePanel = N_oSetupPanel.N_comps.COMP_NAME.BASE_PANEL;
    const baseView = N_oSetupPanel.N_comps.COMP_NAME.BASE_VIEW;
    const graph = N_oSetupPanel.N_comps.COMP_NAME.GRAPH;
    const cBaseForm = N_oSetupPanel.N_comps.COMP_NAME.C_BASE_FORM;
    const treeGrid = N_oSetupPanel.N_comps.COMP_NAME.TREE_GRID;
    const dateNav = N_oSetupPanel.N_comps.COMP_NAME.DATE_NAV;
    const refGraph = N_oSetupPanel.N_comps.COMP_NAME.REF_GRAPH;
    const refBaseGrid = N_oSetupPanel.N_comps.COMP_NAME.REF_BASE_GRID;
    const cloneBasePanel = N_oSetupPanel.N_comps.COMP_NAME.CLONE_BASE_PANEL;
    this.panelItems = {};
    this.panelFieldDetail = {};
    this.selectedLib = [];
    this.selectedLibData = {};
    this.isTreeGridNavMode = false;
    this.m2oOptionsCache = this.GT_command.Tsetup.stored.m2o;
    if (this.current && this.current.name !== '') {
      this.panelItems = this.currentCompClass.GetCompPanelConf().attrLibFeild;
      this.panelFieldDetail = this.currentCompClass.GetCompPanelConf().attrLibFeildDetail;

      const name = this.current.name.toLowerCase();

      if (name === baseGrid.toLowerCase()) {
        this.releaseBaseGrid();
      } else if (name === refBaseGrid.toLowerCase()) {
        this.releaseBaseGrid();
      } else if (name === cBaseForm.toLowerCase()) {
        this.releaseCbaseForm();
      } else if (name === treeGrid.toLowerCase()) {
        this.releaseTreeGrid();
      } else if (name === dateNav.toLowerCase()) {
        this.releaseDateNav();
      } else if (name === basePanel.toLowerCase()) {
        this.releaseBasePanel();
      } else if (name === graph.toLowerCase()) {
        this.releaseGraph();
      } else if (name === refGraph.toLocaleLowerCase()) {
        this.releaseRefGraph();
      } else if (name === baseView.toLowerCase()) {
        this.releaseBaseView();
      } else if (name === cloneBasePanel.toLowerCase()) {
        this.releaseBasePanel();
      }
    }
    this.refreshTableData('reload', this.selectedLibData);
  }

  private releaseBaseGrid() {
    // 组装数据结构
    this.selectedLib = [
      {
        title: '',
        content: [
          {
            title: '',
            list: 'mark_0_0'
          }
        ]
      }
    ];
    // 组装数据
    const columns = this.current.config['tableColumns'];
    this.selectedLibData['mark_0_0'] = columns;
    this.$set(
      this.uniqueIndexes,
      'mark_0',
      this.current.config['uniqueIndexes']
    );
    this.$set(this.indexes, 'mark_0', this.current.config['indexes']);
    this.$set(this.rules, 'mark_0', this.current.config['rules']);
    this.$set(this.headerGroup, 'mark_0', this.current.config['headerGroup']);
    if (!this.current.config['charts']) this.current.config['charts'] = [];
    this.$set(this.charts, 'mark_0', this.current.config['charts']);
    // const defaultFields = baseGridDefaultFields();
    const defaultFields = [...auditDefaultFields(), ...recordsDefaultFields()];
    defaultFields.forEach(itm => {
      if (
        this.selectedLibData['mark_0_0'].findIndex(
          it => it.field === itm.field
        ) < 0
      ) {
        this.selectedLibData['mark_0_0'].push(itm);
      }
    });
    // if (this.selectedLibData['mark_0_0'].length === 0) {
    //   this.selectedLibData['mark_0_0'].push(...baseGridDefaultFields())
    // }
  }

  private releaseCbaseForm() {
    this.selectedLib = [
      {
        // title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.header'),
        title: 'gauge_outfit',
        content: []
      }
    ];

    this.current.config.formPanels.forEach((item: any, idx: number) => {
      const columns = item.content['formColumns'];
      const listName = `mark_0_${idx}`;
      this.selectedLib[0].content[idx] = {
        title: item.label,
        list: listName
      };
      // this.btnDisable[0].children[idx] = true;
      this.selectedLibData[listName] = columns;
      if (idx === 0) {
        this.$set(this.uniqueIndexes, 'mark_0', item.content['uniqueIndexes']);
        this.$set(this.indexes, 'mark_0', item.content['indexes']);
        this.$set(this.rules, 'mark_0', item.content['rules']);
      }
    });
  }

  private releaseTreeGrid() {
    this.isTreeGridNavMode = this.current.config['tableStyle'].mode === 'nav';
    this.sourceTable = this.current.config['tableDataSource'].main.name;
    this.sourceTableID = this.current.config['tableDataSource'].main.id;
    if (
      !Tsrv.utils.isObject(
        this.current.config['tableDataSource'].main.fields[0]
      )
    ) {
      this.current.config['tableDataSource'].main.fields = [];
      this.sourceTable = '';
      this.sourceTableID = null;
    }
  }

  private releaseDateNav() {
    // 组装数据结构
    this.selectedLib = [
      {
        title: '',
        content: [
          {
            title: '',
            list: 'mark_0_0'
          }
        ]
      }
    ];

    // 组装数据
    const columns = this.current.config['tableColumns'];
    this.selectedLibData['mark_0_0'] = columns;
    this.$set(
      this.uniqueIndexes,
      'mark_0',
      this.current.config['uniqueIndexes']
    );
    this.$set(this.indexes, 'mark_0', this.current.config['indexes']);
    this.$set(this.rules, 'mark_0', this.current.config['rules']);
    this.$set(this.headerGroup, 'mark_0', this.current.config['headerGroup']);
    if (!this.current.config['charts']) this.current.config['charts'] = [];
    this.$set(this.charts, 'mark_0', this.current.config['charts']);
  }

  private releaseBasePanel() {
    this.selectedLib = [
      {
        // title: Tsrv.getI18nByPath('oSetupPanel.SetupAttrLibfield.header'),
        title: 'gauge_outfit',
        // title: Tsrv.getI18nBySrv('gauge_outfit'),
        content: []
      }
    ];
    if (Tsrv.getx(this.current.config, 'formPanels', false))
      this.current.config.formPanels.forEach((item: any, idx: number) => {
        const columns = item.content['formColumns'];
        const listName = `mark_0_${idx}`;
        this.selectedLib[0].content[idx] = {
          title: item.label,
          list: listName
        };
        // this.btnDisable[0].children[idx] = true;
        this.selectedLibData[listName] = columns;
        if (idx === 0) {
          this.$set(
            this.uniqueIndexes,
            'mark_0',
            item.content['uniqueIndexes']
          );
          this.$set(this.indexes, 'mark_0', item.content['indexes']);
          this.$set(this.rules, 'mark_0', item.content['rules']);
        }
        // if (this.selectedLibData[listName].length === 0 && idx === 0) {
        // if (idx === 0) {
        //   // 如果是新增单据默认在单头加上字段_status_(单据状态) _audited_(审核状态)，这个2个字段后端不能删除
        //   const defaultFields = [...auditDefaultFields()];
        //   defaultFields.forEach(itm => {
        //     if (
        //       this.selectedLibData[listName].findIndex(
        //         it => it.field === itm.field
        //       ) < 0
        //     ) {
        //       this.selectedLibData[listName].push(itm);
        //     }
        //   });
        //   // this.selectedLibData[listName].push(...auditDefaultFields());
        // }
      });

    if (Tsrv.getx(this.current.config, 'tablePanels', false))
      this.current.config.tablePanels.forEach((item: any, idx: number) => {
        const columns = item.content['tableColumns'];
        const listName = `mark_${idx + 1}_0`;
        this.selectedLib[idx + 1] = {
          title: item.label,
          content: []
        };
        this.selectedLib[idx + 1].content[0] = {
          title: '',
          list: listName
          // btnUnique: {
          //   isShow: true,
          //   disabled: true
          // },
          // btnIndex: {
          //   isShow: true,
          //   disabled: true
          // },
          // btnSelect: {
          //   isShow: true,
          //   disabled: false
          // },
          // btnDelete: {
          //   isShow: true,
          //   disabled: true
          // },
          // btnUp: {
          //   isShow: true,
          //   disabled: true
          // },
          // btnDown: {
          //   isShow: true,
          //   disabled: true
          // },
          // btnGetField: {
          //   isShow: false,
          //   disabled: true
          // }
        };

        this.selectedLibData[listName] = columns;
        const defaultFields = [
          ...auditDefaultFields(),
          ...recordsDefaultFields()
        ];
        defaultFields.forEach(itm => {
          if (
            this.selectedLibData[listName].findIndex(
              it => it.field === itm.field
            ) < 0
          ) {
            this.selectedLibData[listName].push(itm);
          }
        });

        this.$set(
          this.uniqueIndexes,
          `mark_${idx + 1}`,
          item.content['uniqueIndexes']
        );
        this.$set(this.indexes, `mark_${idx + 1}`, item.content['indexes']);
        this.$set(this.rules, `mark_${idx + 1}`, item.content['rules']);
        if (!item.content['headerGroup']) item.content['headerGroup'] = [];
        this.$set(
          this.headerGroup,
          `mark_${idx + 1}`,
          item.content['headerGroup']
        );
        if (!item.content['charts']) item.content['charts'] = [];
        this.$set(this.charts, `mark_${idx + 1}`, item.content['charts']);
      });
  }

  private releaseRefGraph() {
    // 组装数据结构
    this.selectedLib = [
      {
        title: '',
        content: [
          {
            title: '',
            list: 'mark_0_0'
            // btnUnique: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnIndex: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnSelect: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnDelete: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnUp: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnDown: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnGetField: {
            //   isShow: false,
            //   disabled: true
            // }
          }
        ]
      }
    ];

    // 组装数据
    const columns = this.current.config['tableColumns'];
    const nodeColumns = this.current.config['nodeColumns'];
    this.selectedLibData['mark_0_0'] = columns;
    this.$set(
      this.uniqueIndexes,
      'mark_0',
      this.current.config['uniqueIndexes']
    );
    this.$set(this.indexes, 'mark_0', this.current.config['indexes']);
    this.$set(this.rules, 'mark_0', this.current.config['rules']);
    this.$set(this.headerGroup, 'mark_0', this.current.config['headerGroup']);
    if (!this.current.config['charts']) this.current.config['charts'] = [];
    this.$set(this.charts, 'mark_0', this.current.config['charts']);
    if (this.selectedLibData['mark_0_0'].length === 0) {
      // 如果是新增单据默认在单头加上默认字段

      this.selectedLibData['mark_0_0'].push({
        fieldID:
          Tsrv.lexicon.setupRefGraphConf.graphDefFieldMasterBillId.fieldID,
        field: Tsrv.lexicon.setupRefGraphConf.graphDefFieldMasterBillId.field,
        type: Tsrv.lexicon.setupRefGraphConf.graphDefFieldMasterBillId.type,
        isShow: true,
        notNull: false,
        defValue: '',
        // fieldPrefix: {
        //   icon: '',
        //   iconStatus: '',
        //   content: ''
        // },
        // fieldSuffix: {
        //   icon: '',
        //   iconStatus: '',
        //   content: ''
        // },
        placeholder: '',
        comment: '',
        selectionID: null,
        disabled: false,
        defaultFilter: false,
        footerMethod: null,
        formatter: {
          type: '',
          decimal: 0,
          thousandmark: false,
          currency: ''
        },
        // actions: {
        //   dochange: ''
        // },
        actions: [],
        auxProp: '',
        cascadeFilter: '', // 联查过滤
        minWidth: '',
        appWeight: '',
        isDes: false,
        many2one: '',
        align: 'left',
        subQuery: '',
        nodeData: false,
        notDel: true
      });
      this.selectedLibData['mark_0_0'].push({
        fieldID: Tsrv.lexicon.setupRefGraphConf.graphDefFieldGraphLibId.fieldID,
        field: Tsrv.lexicon.setupRefGraphConf.graphDefFieldGraphLibId.field,
        type: Tsrv.lexicon.setupRefGraphConf.graphDefFieldGraphLibId.type,
        isShow: true,
        notNull: false,
        defValue: '',
        // fieldPrefix: {
        //   icon: '',
        //   iconStatus: '',
        //   content: ''
        // },
        // fieldSuffix: {
        //   icon: '',
        //   iconStatus: '',
        //   content: ''
        // },
        placeholder: '',
        comment: '',
        selectionID: null,
        disabled: false,
        defaultFilter: false,
        footerMethod: null,
        formatter: {
          type: '',
          decimal: 0,
          thousandmark: false,
          currency: ''
        },
        // actions: {
        //   dochange: ''
        // },
        actions: [],
        cascadeFilter: '', // 联查过滤
        auxProp: '',
        minWidth: '',
        appWeight: '',
        isDes: false,
        many2one: '',
        align: 'left',
        subQuery: '',
        nodeData: false,
        notDel: true
      });
    }
  }

  private releaseGraph() {
    // 组装数据结构
    this.selectedLib = [
      {
        title: '',
        content: [
          {
            title: '',
            list: 'mark_0_0'
            // btnUnique: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnIndex: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnSelect: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnDelete: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnUp: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnDown: {
            //   isShow: true,
            //   disabled: false
            // },
            // btnGetField: {
            //   isShow: false,
            //   disabled: true
            // }
          }
        ]
      }
    ];

    // 组装数据
    const columns = this.current.config['tableColumns'];
    const nodeColumns = this.current.config['nodeColumns'];
    this.selectedLibData['mark_0_0'] = columns;
    this.$set(
      this.uniqueIndexes,
      'mark_0',
      this.current.config['uniqueIndexes']
    );
    this.$set(this.indexes, 'mark_0', this.current.config['indexes']);
    this.$set(this.rules, 'mark_0', this.current.config['rules']);
    this.$set(this.headerGroup, 'mark_0', this.current.config['headerGroup']);
    if (!this.current.config['charts']) this.current.config['charts'] = [];
    this.$set(this.charts, 'mark_0', this.current.config['charts']);
    if (this.selectedLibData['mark_0_0'].length === 0) {
      // 如果是新增单据默认在单头加上字段
      this.selectedLibData['mark_0_0'].push({
        fieldID: Tsrv.lexicon.setupGraphConf.graphDefFieldNodeId.fieldID,
        field: Tsrv.lexicon.setupGraphConf.graphDefFieldNodeId.field,
        type: Tsrv.lexicon.setupGraphConf.graphDefFieldNodeId.type,
        isShow: true,
        notNull: false,
        defValue: '',
        // fieldPrefix: {
        //   icon: '',
        //   iconStatus: '',
        //   content: ''
        // },
        // fieldSuffix: {
        //   icon: '',
        //   iconStatus: '',
        //   content: ''
        // },
        placeholder: '',
        comment: '',
        selectionID: null,
        disabled: false,
        defaultFilter: false,
        footerMethod: null,
        formatter: {
          type: '',
          decimal: 0,
          thousandmark: false,
          currency: ''
        },
        // actions: {
        //   dochange: ''
        // },
        actions: [],
        auxProp: '',
        cascadeFilter: '', // 联查过滤
        minWidth: '',
        appWeight: '',
        isDes: false,
        many2one: '',
        align: 'left',
        subQuery: '',
        nodeData: false,
        notDel: true
      });
      this.selectedLibData['mark_0_0'].push({
        fieldID: Tsrv.lexicon.setupGraphConf.graphDefFieldMasterBillId.fieldID,
        field: Tsrv.lexicon.setupGraphConf.graphDefFieldMasterBillId.field,
        type: Tsrv.lexicon.setupGraphConf.graphDefFieldMasterBillId.type,
        isShow: true,
        notNull: false,
        defValue: '',
        // fieldPrefix: {
        //   icon: '',
        //   iconStatus: '',
        //   content: ''
        // },
        // fieldSuffix: {
        //   icon: '',
        //   iconStatus: '',
        //   content: ''
        // },
        placeholder: '',
        comment: '',
        selectionID: null,
        disabled: false,
        defaultFilter: false,
        footerMethod: null,
        formatter: {
          type: '',
          decimal: 0,
          thousandmark: false,
          currency: ''
        },
        // actions: {
        //   dochange: ''
        // },
        actions: [],
        auxProp: '',
        cascadeFilter: '', // 联查过滤
        minWidth: '',
        appWeight: '',
        isDes: false,
        many2one: '',
        align: 'left',
        subQuery: '',
        nodeData: false,
        notDel: true
      });
    }
  }

  private releaseBaseView() {
    // 组装数据结构
    this.selectedLib = [
      {
        title: '',
        content: [
          {
            title: '',
            list: 'mark_0_0'
            // btnUnique: {
            //   isShow: false,
            //   disabled: true
            // },
            // btnIndex: {
            //   isShow: false,
            //   disabled: true
            // },
            // btnSelect: {
            //   isShow: false,
            //   disabled: true
            // },
            // btnDelete: {
            //   isShow: false,
            //   disabled: true
            // },
            // btnUp: {
            //   isShow: false,
            //   disabled: true
            // },
            // btnDown: {
            //   isShow: false,
            //   disabled: true
            // },
            // btnGetField: {
            //   isShow: true,
            //   disabled: false
            // }
          }
        ]
      }
    ];

    // 组装数据
    const columns = this.current.config['tableColumns'];
    this.selectedLibData['mark_0_0'] = columns;
    this.$set(
      this.uniqueIndexes,
      'mark_0',
      this.current.config['uniqueIndexes']
    );
    this.$set(this.indexes, 'mark_0', this.current.config['indexes']);
    this.$set(this.rules, 'mark_0', this.current.config['rules']);
    this.$set(this.headerGroup, 'mark_0', this.current.config['headerGroup']);
    if (!this.current.config['charts']) this.current.config['charts'] = [];
    this.$set(this.charts, 'mark_0', this.current.config['charts']);
  }

  /**
   * 保存改变
   */
  private saveChanges() {
    this.$emit('save-changes');
  }

  private m2oChange(editingLibIndex: number, editingLibSubIndex: number) {
    this.m2oAndSclDataLinkChange(editingLibIndex, editingLibSubIndex);
    this.saveChanges();
  }

  private slcChange(editingLibIndex: number, editingLibSubIndex: number) {
    this.m2oAndSclDataLinkChange(editingLibIndex, editingLibSubIndex);
    this.saveChanges();
  }

  // 检查整串json 是否合法 替换
  private strChange(o, k, v) {
    v = v.replace(/[\r\n]/g, ' ').trim();
    o[k] = v;
    this.saveChanges();
  }

  refTableChange(v) {
    if (this.currentCompClass instanceof T_refBaseGrid) {
      this.current.config.refTable = v;
    }
    this.saveChanges();
  }

  private cascadeFilterChange(
    editingLibIndex: number,
    editingLibSubIndex: number
  ) {
    this.m2oAndSclDataLinkChange(editingLibIndex, editingLibSubIndex);
    this.saveChanges();
  }

  private m2oAndSclDataLinkChange(
    editingLibIndex: number,
    editingLibSubIndex: number
  ) {
    if (
      Tsrv.utils.noValue(
        this.selectedLibData[editingLibIndex][editingLibSubIndex].many2one
          .toTable
      ) &&
      Tsrv.utils.noValue(
        this.selectedLibData[editingLibIndex][editingLibSubIndex].selectionID
      )
    ) {
      this.selectedLibData[editingLibIndex][editingLibSubIndex].cascadeFilter =
        '';
    }
  }

  /**
   * 根据字段名获取table的index
   */
  private getTableIndexByField(field: string) {
    const index = this.activeGroup;
    let subIndex = 0;
    while (this.selectedLibData[`mark_${index}_${subIndex}`]) {
      const data = this.selectedLibData[`mark_${index}_${subIndex}`];
      if (Tsrv.utils.find(data, item => item.field === field)) {
        break;
      }
      subIndex++;
    }
    return `mark_${index}_${subIndex}`;
  }

  /**
   * 根据数据库格式获取字段类型
   */
  private getFieldInfoByDBType(dbType: string) {
    let type = dbType;
    let general = '';
    let specific = '';
    const lengthArr = dbType.match(/\(([^)]*)\)/);
    let length: number | null = null;
    if (lengthArr !== null) {
      type = type.replace(/\(.*?\)/, '');
      length = Tsrv.utils.toNumber(lengthArr[1]);
    }

    switch (type) {
      case 'smallint':
        specific = 'int';
        general = 'number';
        break;
      case 'bigint':
        specific = 'int';
        general = 'number';
        break;

      case 'int':
        specific = 'int';
        general = 'number';
        break;
      case 'dec':
        specific = 'dec';
        general = 'number';
        break;
      case 'decimal':
        specific = 'dec';
        general = 'number';
        break;
      case 'varchar':
        general = 'text';
        break;

      case 'tinytext':
        general = 'text';
        break;
      case 'text':
        general = 'text';
        break;
      case 'mediumtext':
        general = 'text';
        break;
      case 'json':
        general = 'json';
        break;

      default:
        break;
    }
    return {
      general,
      specific,
      length
    };
  }

  /**
   * 分组切换显示
   */
  private groupSwitch(index: number) {
    this.activeGroup = index === this.activeGroup ? undefined : index;
  }

  /**
   * 隐藏详情
   */
  private hideDetailPanel() {
    const that = this;
    this.detailPanelStyle = {
      display: 'none'
    };
    this.m2oOptions = [];
    this.detailSelectionID = null;

    this.editingLibSubIndex = null;
  }

  /**
   * 显示详情
   */
  private showDetailPanel(params: any) {
    if (this.activeGroup !== undefined && params) {
      const that = this;
      const editingLibIndex = Tsrv.utils.clone(this.editingLibIndex, true);
      const editingLibSubIndex = Tsrv.utils.clone(
        this.editingLibSubIndex,
        true
      );
      this.m2oOptions = [];
      this.detailSelectionID = null;
      this.editingLibSubIndex = null;
      const field = params.row.field;
      //   // 设置当前编辑表和字段
      this.editingLibIndex = this.getTableIndexByField(field);
      this.editingLibSubIndex = params.index;
      // 设置当前字段的类型
      const type = this.getFieldInfoByDBType(params.row.type);
      this.editingLibType = type.general;
      this.editingLibSpeType = type.specific;
      const actions = this.selectedLibData[this.editingLibIndex][
        this.editingLibSubIndex
      ].actions;

      // if (actions) {
      //   if (!actions.dochange) actions.dochange = false;
      // }
      // 切换字段时 清空 子查询来源信息
      if (
        editingLibIndex !== this.editingLibIndex ||
        editingLibSubIndex !== this.editingLibSubIndex
      ) {
        this.sqlSourceTable = '';
        this.sqlSourceField = '';
      }
      this.detailPanelStyle = {
        display: 'flex'
      };
    }
  }

  public getRef(eleName: string, idx: number, idx2: number) {
    const refName: string = `ref${Tsrv.utils.custUUID(4)}`;
    this.setEleRef(`${eleName}${idx}${idx2}`, refName);
    return refName;
  }

  loadTableData() {
    this.refreshTableData('reload', this.selectedLibData);
  }

  getFields(index: number, subIndex: number, name: string) {
    // 清除
    const currentTableName = this.selectedLib[index].content[subIndex].list;
    this.selectedLibData[currentTableName].splice(0);
    this.refreshTableData('reload', this.selectedLibData);

    if (this.currentCompClass instanceof T_refBaseGrid) {
      const p = {
        dbType: this.current.config.dbType,
        funName: this.refTable
      };
      if (p.dbType === '' || p.funName === '') {
        this.$msg(Tsrv.getI18nByValue('还未定义功能名'));
        return;
      }
      // this.getSchemaData(p, index, subIndex, Tsrv.url.getFun);
      this.getFunColumnConf(p, index, subIndex);
    }
    if (this.currentCompClass instanceof T_baseView) {
      const p = {
        dbType: this.current.config.dbType,
        viewName: this.current.config.name
      };
      if (p.dbType === '' || p.viewName === '') {
        this.$msg(Tsrv.getI18nByValue('还未定义功能名'));
        return;
      }
      this.getSchemaData(p, index, subIndex, Tsrv.url.getView);
    }
  }

  private getSchemaData(p: any, index: number, subIndex: number, url: string) {
    Tsrv.standardPostReq<ifs.I_setDataRes, any>(p, url)
      .then(([res, msg]) => {
        this.$msg(msg ?? res.msg);
        const data: Array<any> = [];
        if (res.success) {
          if (Tsrv.utils.noValue(res.data)) {
            this.$msg(Tsrv.getI18nByValue('未返回数据'));
          } else {
            res.data.forEach(ele => {
              data.push({
                id: '-1',
                title: ele.colName,
                data_type: ele.dataType
              });
            });
            this.addFieldsToTable(data, index, subIndex);
          }
        }
      })
      .catch(err => {
        throw new Error(err);
      });
  }

  private getFunColumnConf(p: any, index: number, subIndex: number) {
    const funInfo = Tsrv.getMainFunInfoByFunName(p.funName);
    if (Tsrv.utils.noValue(funInfo)) {
      Tsrv.reqGetFunInfo(p.funName).then(fInfo => {
        if (!Tsrv.utils.noValue(fInfo)) {
          this.$store.commit('SET_FUNINFO', {
            key: fInfo.mainFun,
            val: fInfo
          });
          Tsrv.getFunConf(p.funName).then(res => {
            if (res.isErr()) {
              console.error(res.errmsg);
            } else {
              this.setFieldsByFunConf(
                res.getReturnData(p.funName),
                index,
                subIndex
              );
            }
          });
        }
      });
    } else {
      Tsrv.getFunConf(p.funName).then(res => {
        if (res.isErr()) {
          console.error(res.errmsg);
        } else {
          this.setFieldsByFunConf(
            res.getReturnData(p.funName),
            index,
            subIndex
          );
        }
      });
    }
  }

  private setFieldsByFunConf(funConf: any, index: number, subIndex: number) {
    if (Tsrv.utils.noValue(funConf?.tableColumns)) {
      return;
    }
    const currentTableName = this.selectedLib[index].content[subIndex].list;
    funConf.tableColumns.forEach(element => {
      this.selectedLibData[currentTableName].push(
        Tsrv.utils.clone(element, true)
      );
    });
    this.refreshTableData('add', this.selectedLibData);
    this.saveChanges();
  }

  private getPanelTableName() {
    const current = this.GT_command.Tsetup.component.current;
    if (current.name === N_oSetupPanel.N_comps.COMP_NAME.BASE_PANEL) {
      current.config.tablePanels.forEach(el => {
        this.panelTabelName.push(el.label);
      });
    }
  }
}
</script>
<style scoped lang="scss">
.treegrid-source {
  .title {
    font-weight: bold;
    height: 36px;
    display: block;
    line-height: 36px;
  }
  .source-title {
    span {
      vertical-align: top;
      margin-right: 15px;
    }
    & {
      padding: 0 0 8px 0;
      line-height: 24px;
    }
    div {
      display: inline-block;
      button {
        float: right;
      }
      button:not(:last-child) {
        margin-left: 10px;
      }
    }
  }
}
.ref-table {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  margin-top: 5px;
  .ref-title {
    margin-right: 10px;
    line-height: 2.5;
    white-space: nowrap;
    font-weight: bold;
  }
  .o-m2o-selector {
    width: 100%;
  }
}
.lib-group {
  border-radius: var(--default-border-radius-base);
  margin-bottom: 5px;
  > .title {
    display: none;
    font-weight: bold;
    height: 36px;
    line-height: 36px;
    margin-bottom: -10px;
  }
  .group-content {
    display: none;
    padding: 7px 0 14px;
  }
  .group-title {
    height: 36px;
    width: 100%;
    border-radius: var(--default-border-radius-base);
    background-color: #e7e8e9;
    cursor: pointer;
    line-height: 36px;
    padding: 0 14px;
    .ivu-icon {
      transition: none;
      float: right;
      padding: 12px 5px;
      cursor: pointer;
      margin-right: -5px;
    }
  }
  .group-func {
    display: inline-block;
    height: 36px;
    padding: 6px 0px;
    line-height: 24px;
    width: fit-content;
    margin-right: 10%;
    // float: left;
    button {
      float: left;
      margin-right: 10px;
    }
  }
  .lib-group-section {
    background-color: #fafbfb;
    padding: 10px 14px;
    margin: 10px 0;
    border-radius: var(--default-border-radius-base);
    .group-section-title {
      // width: 100%;
      display: inline-block;
      height: 36px;
      padding: 6px 0;
      line-height: 24px;
      button {
        float: right;
      }
      button:not(:last-child) {
        margin-left: 10px;
      }
    }
  }
}
.active {
  border-radius: var(--default-border-radius-base);
  .group-content {
    display: block;
  }
  .group-title {
    .ivu-icon {
      transform: rotate(-180deg);
    }
  }
}
.no-group {
  > .title {
    display: block;
  }
  .group-title {
    display: none;
  }
  .lib-group-section {
    padding: 0;
    background-color: #fff;
  }
  // .group-func {
  //   margin-bottom: -46px;
  // }
}
.detail-panel {
  position: absolute;
  left: -360px;
  top: 0;
  z-index: 10;
  height: 100%;
  width: 100%;
  background-color: #fff;
  display: none;
  // transform: translateX(-360px);   //clr---改成card-box后不能平排显示暂时叠加显示23013
  flex-direction: column;
  transition: ease-in-out 0.2s;
  overflow-y: auto;
  border-left: 1px solid #dddddd;
  box-shadow: rgba(0, 0, 0, 0.05) -1px 0 1px;
  .title {
    display: block;
    height: 36px;
    line-height: 36px;
    font-weight: bold;
    padding: 0 15px;
    background-color: #eee;
    position: sticky;
    top: 0;
    z-index: 4;
    display: flex;
    justify-content: space-between;
    .sel-row-field {
      // color: #f40;
      font-weight: 400;
    }
    span {
      cursor: pointer;
      float: left;
    }
    .ivu-icon {
      font-size: 18px;
      float: right;
      line-height: 36px;
      cursor: pointer;
    }
  }
  .detail-panel-box {
    display: flex;
    flex-direction: column;
    line-height: 36px;
    flex-wrap: wrap;
    align-items: center;
    span {
      padding: 0 10px;
      text-align: left;
    }
    .check {
      display: flex;
      width: 33.33%;
      padding-left: 10px;
      font {
        // text-overflow: ellipsis;
        // overflow: hidden;
        // white-space: nowrap;
        // width: 80%;
        line-height: 20px;
        width: 80%;
        margin-bottom: 10px;
        float: left;
      }
    }
    .input {
      display: flex;
      flex-direction: column;
      width: 100%;
      padding: 0 10px;
      .ivu-input-wrapper,
      .ivu-input-number,
      .o-m2o-selector,
      .o-m2o-editor {
        width: calc(100% - 20px);
        margin: 0 10px;
        // height: 30px;
      }
      .ivu-input-type-textarea {
        height: auto;
      }
    }
    .select {
      display: flex;
      flex-direction: column;
      width: 100%;
      padding: 0 10px;
      .ivu-select {
        margin: 0 10px;
        width: calc(100% - 20px);
      }
    }
    .formatter {
      width: 100%;
      padding: 0 10px;
    }
    .o-formatter-setting {
      width: 100%;
      padding: 0 20px;
    }
    .o-i18n-selector ::v-deep {
      width: calc(100% - 20px);
      margin: 0 10px;
      height: 30px;
      .i18n-icon {
        top: 3.5px;
      }
      .item-render {
        top: 4px;
      }
    }
    // .formatter {
    //   width: 100%;
    //   padding: 0 10px;
    //   .input {
    //     span {
    //       padding: 0;
    //     }
    //   }
    //   .formatter-decnum,
    //   .formatter-spliter,
    //   .formatter-currency {
    //     width: 50%;
    //     float: left;
    //     margin-top: 15px;
    //   }
    // }
    .many2one {
      width: 100%;
      padding: 0 10px;
      display: flex;
      flex-direction: column;
      .ivu-select {
        padding: 0 10px;
      }
    }
    .selectionID {
      width: 100%;
      padding: 5px 10px;
      button {
        float: right;
        margin: 5px 10px 5px 0;
      }
    }
    .actions {
      width: 100%;
      padding: 0 10px;
      display: flex;
      flex-direction: column;
      .ivu-input {
        height: 30px;
      }
    }
    .actions-dochange {
      display: flex;
      flex-direction: row;
      padding: 0 20px;
      width: 100%;
      justify-content: space-between;
      i {
        font-style: normal;
        flex-shrink: 0;
        padding-right: 10px;
      }
      span {
        top: 6px;
      }
    }
  }
  .box-h {
    flex-direction: row;
  }
}
.index-cell {
  margin-bottom: 10px;
  border-radius: 10px;
  background-color: #7594b5;
  position: relative;
  text-align: center;
  line-height: 40px;
  color: #fff;
  .index-cell-id {
    width: 50px;
    display: block;
    float: left;
    border-right: 1px solid rgba(255, 255, 255, 0.4);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-break: keep-all;
  }
  .index-cell-name,
  .index-cell-name-i18n {
    width: calc(50% - 40px);
    display: block;
    float: left;
  }
  .index-cell-name {
    border-right: 1px solid rgba(255, 255, 255, 0.4);
  }
  .index-cell-tit {
    height: 40px;
    width: 100%;
    position: relative;
    border-bottom: 1px solid rgba(255, 255, 255, 0.4);
    .ivu-icon {
      position: absolute;
      right: 18px;
      top: 12px;
      font-size: 15px;
      cursor: pointer;
    }
  }
  .index-cell-cont {
    height: 40px;
    width: 100%;
  }
}
.unique-index .index-cell {
  background-color: #5d9092;
}
.subquery {
  position: relative;
  .input > .ivu-btn {
    position: absolute;
    right: 20px;
    top: 6px;
  }
  .subquery-box {
    display: flex;
    flex-direction: row;
    margin-bottom: 15px;
    > .ivu-input-wrapper {
      top: 3px;
    }
  }
}
.selected-lib {
  .title {
    top: 0;
    left: 0;
    background-color: #fff;
  }
  button {
    float: right;
    margin: 6px 10px 6px 0;
  }
  .lib-add {
    float: right;
    margin: 6px 0px;
  }
  .lib-get-field {
    float: right;
    margin: 6px 0px;
  }
  .selected-lib-table ::v-deep {
    margin: 7px 0;
    overflow: auto;
    .ivu-icon {
      cursor: pointer;
      font-size: 14px;
      padding: 6px;
      border-radius: 100%;
      &:hover {
        background-color: #e6e6e7;
      }
    }
    .ivu-table-header thead tr th {
      text-align: center;
    }
    .ivu-table-cell {
      padding: 0;
    }
    input {
      height: 47px;
      border: none;
      background-color: transparent;
    }
  }
}
.source-table ::v-deep {
  .ivu-table-cell {
    padding: 0;
    padding-left: 8px;
    padding-right: 8px;
  }
}
</style>
